鉴于这个类是enable_shared_from_this:
class connection : public std::enable_shared_from_this<connection>
{
//...
};
假设我从 same connection*
创建了两个 std::shared_ptr
实例,如下所示:
std::shared_ptr<connection> rc(new connection);
std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
std::cout << "fake delete" << std::endl;
});
到目前为止一切正常,因为资源 { connection*
} 由单个 shared_ptr
— rc
准确地说,fc
只是有一个假的删除器。
之后,我这样做:
auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!
现在 shared_ptr
— rc
或 fc
— sc
将共享其 reference-count 与?换句话说,
std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;
这些应该打印什么?我测试了这段代码和 found rc
似乎有 2
引用,而 fc
只有 1
。
我的问题是,这是为什么?什么是正确的行为及其理由?
我使用的是 C++11 和 GCC 4.7.3。
最佳答案
The raw pointer overloads assume ownership of the pointed-to object. Therefore, constructing a shared_ptr using the raw pointer overload for an object that is already managed by a shared_ptr, such as by
shared_ptr(ptr.get())
is likely to lead to undefined behavior, even if the object is of a type derived fromstd::enable_shared_from_this
. -- http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
在您的情况下,您得到的共享指针具有两个不同的所有权信息 block ,但始终会增加该类的第一个共享指针实例的引用计数。
如果您删除“假删除器”,您会遇到双重免费问题。
关于c++ - 来自同一个 enable_shared_from_this 实例的两个 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257218/