[英]Proper use of boost::shared_ptr in a list
I have a question related to boost::shared_ptr<>
in C++. 我有一个与C ++中的boost::shared_ptr<>
相关的问题。 I am currently willing to perform a smart deletion of the items of my list: 我目前愿意对列表中的项目进行智能删除:
This is a behavior required by my program. 这是我的程序要求的行为。
I am really wondering how to do that properly since the std::list<boost::shared_ptr<object> >
remove/erase functions causes the deletion of the shared_ptr<>
and therefore of the real object. 我真的很想知道如何正确地执行此操作,因为std::list<boost::shared_ptr<object> >
remove / erase函数会导致shared_ptr<>
的删除,从而导致真实对象的删除。
So I finally came up with this solution: use a std::list<object*>
and inherit object
from boost::enable_shared_from_this<>
. 所以我终于想出了这个解决方案:使用std::list<object*>
并从boost::enable_shared_from_this<>
继承object
。 That way, when someone needs to use an item from the list, I give them object->shared_from_this()
. 这样,当有人需要使用列表中的项目时,我给他们提供object->shared_from_this()
。
My questions are the following: 我的问题如下:
boost::shared_ptr<>
associated to shared_from_this()
takes into consideration the reference to the object in the list ? 与shared_from_this()
关联的boost::shared_ptr<>
是否考虑对列表中对象的引用? I hope my question is explicit enough and that someone will be able to help me. 我希望我的问题足够明确,希望有人能够帮助我。 The proper use of the smart pointers in lists is something I'd like to be able to use. 我希望能够正确使用列表中的智能指针。
Thank you 谢谢
When you delete a shared_ptr
you don't delete the real object unless it is not used anywhere else. 删除shared_ptr
,除非没有在其他地方使用它,否则不会删除该真实对象。 That's the whole point about using shared_ptr
. 这就是使用shared_ptr
。
For instance, if you take one element of the list, copy it and give it to another function, then delete the element from the list, the real object won't be deleted because it is still referenced somewhere else. 例如,如果您使用列表中的一个元素,将其复制并提供给另一个函数,然后从列表中删除该元素,则不会删除真实对象,因为它仍然在其他地方被引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.