问题描述
我记得在某处使用引用智能指针可能会导致内存损坏。这是否仅仅是因为智能指针在被销毁后使用的引用?
I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up?
感谢您澄清
推荐答案
p>假设你正在谈论shared_ptr在这里...
Assuming you are talking about shared_ptr here...
这是一个很好的答案。你可能不知道绝对的指针的生命周期。
This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too.
为了解决这个问题,你需要查看boost :: weak_ptr。它不参与引用计数。当你需要使用它,它给你一个shared_ptr,一旦你做了它会消失。它也将让你知道什么时候指针已经收集。
To get around this, you'd want to look into boost::weak_ptr. It doesn't participate in reference counting. When you need to use it, it gives you a shared_ptr which goes away once your done with it. It will also let you know when the refered to pointer has been collected.
从文档
注意,方法expired()也会告诉你ptr是否还在。
Note the method expired() will also tell you if your ptr is still around.
这篇关于为什么不应该使用智能指针的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!