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.