gpt4 book ai didi

c++ - 我能知道调用者是否保留了共享指针的拷贝吗?

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:15 24 4
gpt4 key购买 nike

假设我有一个像这样的函数 f:

class MyClass {
};

boost::shared_ptr<MyClass> f(/*other input parameters*/) {
static boost::shared_ptr<MyClass> p;
if (!p.get() || /*Test if somebody else has a copy of my pointer*/) {
p.reset(new MyClass() );
}

/*Do other stuff*/

return p;
}

我可以检查调用者是否保留了我的指针的拷贝吗?如果我释放我的指针,他也释放他的指针,内存会释放吗?

最佳答案

Can I check if the caller retained a copy of my pointer?

不,正如弗拉德所说,你真的不应该想知道。有这个 use_count 函数,但是 boost 警告不要使用它。

Notes: use_count() is not necessarily efficient. Use only for debugging and testing purposes, not for production code.

关于你的第二个问题,

If I release my pointer, and he also releases his pointer, will be the memory released?

答案是肯定的,前提是所有权仅在这两个实例之间共享。

关于c++ - 我能知道调用者是否保留了共享指针的拷贝吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com