I have a class that I know will always belong std::shared_ptr. However, the transfer, shared_ptror even weak_ptrfunctions and methods that do not require property rights or lifetime guarantees, creates unnecessary overhead. To get around this, I often pass in source function pointers. The class itself is inherited from std::enable_shared_from_this, therefore, if the function should take responsibility for the pointer, it can use the class method to get it shared_ptr.
All of this works great. However, there are cases when I do not want to make shared_ptrfrom a raw pointer, instead I want to weak_ptr.
From what I understand about a regular implementation 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 weak_ptr, I must first create shared_ptrand convert it. This means that link counts are changed as follows:
- Construct
shared_ptr, increment shared_ptrcounter - Copy construct
weak_ptr, increment weak_ptrcounter - Allow
shared_ptrout of scope, decrease shared_ptrcounter
This seems to contradict the idea that "you are not paying for what you are not using." Is there a way for my class to simply provide weak_ptrwithout first creating it shared_ptr?