Naw*_*waz 6 c++ reference-counting shared-ptr weak-ptr enable-shared-from-this
鉴于此类是enable_shared_from_this:
class connection : public std::enable_shared_from_this<connection>
{
//...
};
Run Code Online (Sandbox Code Playgroud)
假设我创建的两个实例std::shared_ptr来自同一 connection*如下:
std::shared_ptr<connection> rc(new connection);
std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
std::cout << "fake delete" << std::endl;
});
Run Code Online (Sandbox Code Playgroud)
到目前为止它的好处,因为资源{ connection*}由一个单独 拥有shared_ptr- rc确切地说,并且fc只有一个假的删除器.
在那之后,我这样做:
auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!
Run Code Online (Sandbox Code Playgroud)
现在哪个shared_ptr- rc或fc- 将sc 与其分享其引用计数?换一种说法,
std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;
Run Code Online (Sandbox Code Playgroud)
这些打印应该是什么?我测试了这个代码,并FOUND rc似乎有2引用,而fc只是1.
我的问题是,为什么?什么应该是正确的行为及其理由?
我正在使用C++ 11和GCC 4.7.3.
原始指针重载假定所指向对象的所有权。因此,使用已由shared_ptr(例如by)管理的对象的原始指针重载构造shared_ptr
shared_ptr(ptr.get())可能会导致未定义的行为,即使该对象的类型派生自std::enable_shared_from_this。-- http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
在您的情况下,您将获得具有两个不同所有权信息块的共享指针,但始终会增加该类的第一个共享指针实例的引用计数。
如果您删除“假删除程序”,您将遇到双重免费问题。
| 归档时间: |
|
| 查看次数: |
482 次 |
| 最近记录: |