Given this class which is enable_shared_from_this:
class connection : public std::enable_shared_from_this<connection>
{
//...
};
Suppose I create two instances of std::shared_ptr
from the same connection*
as follows:
std::shared_ptr<connection> rc(new connection);
std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
std::cout << "fake delete" << std::endl;
});
So far its good, as the resource { connection*
} is owned by a single shared_ptr
— rc
to be precise, and fc
just have a fake deleter.
After that, I do this:
auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!
Now which shared_ptr
— rc
or fc
— would sc
share its reference-count with? In other words,
std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;
What should these print? I tested this code and found rc
seems to have 2
references while fc
just 1
.
My question is, why is that? and what should be the correct behavior and its rationale?
I'm using C++11 and GCC 4.7.3.
when all shared_ptr's pointing to resource goes out of scope the resource is destroyed. A weak_ptr is created as a copy of shared_ptr. It provides access to an object that is owned by one or more shared_ptr instances but does not participate in reference counting.
std::shared_ptr. std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.
hpp> defines the class template enable_shared_from_this . It is used as a base class that allows a shared_ptr or a weak_ptr to the current object to be obtained from within a member function.
std::enable_shared_from_this is a standard solution that enables a shared_ptr managed object to acquire a shared_ptr to itself on demand. A class T that publicly inherits an std::enable_shared_from_this<T> encapsulates a std::weak_ptr<T> to itself that can be converted to a std::shared_ptr<T> when needed.
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
In your case you get to shared pointers that have two different ownership information blocks but always increment the ref count of the first shared pointer instance of the class.
If you remove the 'fake deleter' you'l get a double free problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With