C++ shared_ptr如何删除具有多个shared_ptr的指针

发布于 2024-09-27 07:17:18 字数 92 浏览 7 评论 0原文

我正在研究这个项目,

我遇到的问题是,当我需要它时,该对象并没有真正被删除,因为它有几个指向它的共享指针。

我该如何解决这个问题,请帮忙。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鸢与 2024-10-04 07:17:18

这是设计使然。只要一个对象被一个或多个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.

失眠症患者 2024-10-04 07:17:18

您可以使用 reset() 方法减少 shared_ptr 的 use_count。

如果您对保存实例的每个指针都执行此操作,则最后一个 reset() 将销毁它指向的对象。

shared_ptr<Class> myPointer1( new Class() ); //myPointer holds an instance of Class
shared_ptr<Class> myPointer2 = myPointer1; //use_count == 2
myPointer1.reset(); //use_count == 1
myPointer2.reset(); //instance of class will be destroyed

但是你的设计可能有问题,当某些对象被销毁或方法结束时,shared_ptr应该自动失去焦点。也许您应该查看shared_ptr 仍然保存指向对象的指针的点,并检查它们是否不应再保存该对象。

You can decrease the use_count of a shared_ptr by using its reset() method.

If you do this for every pointer which holds the instance, the last reset() will destroy the object it points to.

shared_ptr<Class> myPointer1( new Class() ); //myPointer holds an instance of Class
shared_ptr<Class> myPointer2 = myPointer1; //use_count == 2
myPointer1.reset(); //use_count == 1
myPointer2.reset(); //instance of class will be destroyed

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文