简体   繁体   English

什么时候std :: shared_ptr释放它的对象?

[英]When does std::shared_ptr release its object?

I'm on Ubuntu 14.04 using GCC 4.8.4 and I have code similar to the following: 我使用GCC 4.8.4在Ubuntu 14.04上,我的代码类似于以下内容:

std::shared_ptr<MyClass> my_shared_object = set elsewhere...
MyFunction(*my_shared_object);

Where MyFunction 's signature looks like this: MyFunction的签名如下:

void MyFunction(const MyClass& my_object)

The full code can be found here 完整的代码可以在这里找到

However, I am finding that my_object actually goes out of scope within the context of MyFunction . 但是,我发现my_object实际上超出了MyFunction范围内的范围。 My thought was that the my_shared_object will only release its contents once it goes out of scope, meaning after the MyFunction has returned. 我的想法是my_shared_object只有在超出范围后才会释放其内容,这意味着在MyFunction返回后。 I am not sure if I am either misunderstanding std::shared_ptr or if maybe this is a GCC bug. 我不确定我是误解std::shared_ptr还是可能这是一个GCC错误。

I guess the question boils down to: when I dereference a std::shared_ptr, does that guarantee that the std::shared_ptr will persist as long as the dereference is being used? 我想问题归结为: 当我取消引用std :: shared_ptr时,这是否保证只要使用取消引用, std::shared_ptr就会持久存在?

Whatever is managed by a std::shared_ptr will be destroyed the moment there's no std::shared_ptr left asserting a claim, all other ways to refer to it are irrelevant. 无论std::shared_ptr管理什么,都会在没有std::shared_ptr声明声明的情况下被破坏,所有其他引用它的方式都无关紧要。

And local variables are only destroyed upon leaving the respective scope. 并且局部变量仅在离开相应范围时被销毁。 Dereferencing a std::shared_ptr does not modify it in any way. 取消引用std::shared_ptr不会以任何方式修改它。

std::shared_ptr doesn't know about your reference (or your reference doesn't know about the std::shared_ptr ) to the object being held, it's aware only of other std::shared_ptr s sharing the ownership of the same object. std::shared_ptr不知道你所引用的对象的引用(或你的引用不知道std::shared_ptr ),它只知道共享同一对象所有权的其他std::shared_ptr Therefore, as soon as the last std::shared_ptr goes out of scope, the object gets destructed and you end up with a dangling reference. 因此,只要最后一个std::shared_ptr超出范围,对象就会被破坏,最终会有一个悬空引用。

However, that should not be the case here and your std::shared_ptr should get properly destructed after the program flow leaves its scope, which I don't understand how, could happen before the call to MyFunction . 但是,这不应该是这种情况,并且在程序流离开其范围之后应该正确地破坏你的std::shared_ptr ,我不明白如何在调用MyFunction之前发生。

std::shared_ptr's maintain an internal reference count. std :: shared_ptr维护内部引用计数。 This count corresponds to number of objects sharing the object. 此计数对应于共享对象的对象数。 Everytime a shared_ptr goes out of scope, the internal reference count is decremented. 每当shared_ptr超出范围时,内部引用计数就会递减。 when the internal reference count falls to zero, the memory is de-allocated. 当内部引用计数降至零时,将取消分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM