为什么不应该使用智能指针的引用? [英] Why shouldn't you use references to smart pointers?

查看:1686
本文介绍了为什么不应该使用智能指针的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得在某处使用引用智能指针可能会导致内存损坏。这是否仅仅是因为智能指针在被销毁后使用的引用?

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...


这只是因为使用智能指针的
引用后
它被销毁?

Is this simply because of using the reference of the smart pointer after its been destroyed?

这是一个很好的答案。你可能不知道绝对的指针的生命周期。

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.

weak_ptr 文档


weak_ptr类模板将
弱引用存储到
的对象由shared_ptr管理。要
访问对象,可以使用
shared_ptr构造函数或成员
函数锁将weak_ptr转换为shared_ptr
。当对象的最后
shared_ptr消失并且对象被删除时,尝试
从引用被删除的
的weak_ptr
实例获得shared_ptr对象将失败:构造函数将
抛出类型
boost :: bad_weak_ptr的异常,并且
weak_ptr :: lock将返回一个空的
shared_ptr。

The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock. When the last shared_ptr to the object goes away and the object is deleted, the attempt to obtain a shared_ptr from the weak_ptr instances that refer to the deleted object will fail: the constructor will throw an exception of type boost::bad_weak_ptr, and weak_ptr::lock will return an empty shared_ptr.

注意,方法expired()也会告诉你ptr是否还在。

Note the method expired() will also tell you if your ptr is still around.

这篇关于为什么不应该使用智能指针的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆