C++ shared_ptr如何删除具有多个shared_ptr的指针
我正在研究这个项目,
我遇到的问题是,当我需要它时,该对象并没有真正被删除,因为它有几个指向它的共享指针。
我该如何解决这个问题,请帮忙。
Im working on this project,
The problem Im having is that the an object, does not really get deleted when I need it to be because it has a couple of shared pointers pointing to it.
How do I solve this,please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是设计使然。只要一个对象被一个或多个
shared_ptr
智能指针拥有,它就不会被销毁。对象的所有权由所有拥有所有权的智能指针共享,并且在所有所有者都使用完该对象之前,该对象无法被销毁。这就是共享所有权。如果您希望能够在仍有一些引用的情况下销毁该对象,则可以对这些引用使用
weak_ptr
。This is by design. As long as an object is owned by one or more
shared_ptr
smart pointers, it will not be destroyed. Ownership of the object is shared by all of the smart pointers that have ownership and the object can't be destroyed until all of the owners are done with it. This is what shared ownership is.If you want to be able to destroy the object while there are still some references to it, you can use
weak_ptr
for those references.您可以使用
reset()
方法减少shared_ptr
的 use_count。如果您对保存实例的每个指针都执行此操作,则最后一个
reset()
将销毁它指向的对象。但是你的设计可能有问题,当某些对象被销毁或方法结束时,shared_ptr应该自动失去焦点。也许您应该查看shared_ptr 仍然保存指向对象的指针的点,并检查它们是否不应再保存该对象。
You can decrease the use_count of a
shared_ptr
by using itsreset()
method.If you do this for every pointer which holds the instance, the last
reset()
will destroy the object it points to.But you probably have a problem with you design, shared_ptr should automatically go out of focus when certain objects are destroyed or methods end. Perhaps you should have a look at the points where the shared_ptrs still hold pointers to the object and check if they shouldn't hold the object anymore.