I have a class which I know will always be owned by a std::shared_ptr
. However passing shared_ptr
or even weak_ptr
to functions and methods that don't need ownership or lifetime guarantees creates unnecessary overhead. To get around this I often pass raw pointers to functions. The class itself inherits from std::enable_shared_from_this
so if the function needs to take ownership of the pointer it can use a method of the class to get a shared_ptr
.
This is all working beautifully. However there are occasions where I don't really want to make a shared_ptr
from a raw pointer, what I want instead is a weak_ptr
.
From what I understand of the usual implementation of std::shared_ptr
it has two atomic variables used as reference counters; one for shared_ptr
, one for weak_ptr
.
If all I have is a raw pointer to my class and I want a weak_ptr
, I must first create a shared_ptr
and convert it. Doing so means the reference counters are altered like this:
shared_ptr
, increment shared_ptr
counterweak_ptr
, increment weak_ptr
countershared_ptr
to go out of scope, decrement shared_ptr
counterThis seems to go against the idea that "you don't pay for what you don't use". Is there a way for my class to just provide weak_ptr
without first creating a shared_ptr
?
Proposal P0033 was accepted for C++17 in the October 2015 meeting, which adds weak_from_this
to classes deriving from std::enable_shared_from_this
.