Search code examples
c++shared-ptrsmart-pointersreference-counting

Are there some smarter smart pointers in C++?


Quite often I work with an old code where raw pointers are mixed with smart ones and I don't have the time to change all raw ones to smart.

And there can be some situations like static raw pointer pointing to an object, which can be already destructed and at first it seems like a situation to use weak_ptr to hold the reference, but there the problem arises, because the place with raw pointer does not have any information about shared_ptrs already pointing to the same object.

So:
1) Is there any smarter smart pointer that tracks all pointers (both raw and smart) to an object?
2) Is there any smarter smart pointer that at least tracks all shared_ptrs to an object?

I don't want a discussion about an implementation, if possible I want to use it as a black-box.

EDIT: I asked 2), because for example calling make_shared on an object twice, makes 2 separate shared_ptr reference counters.


Solution

  • 1) Is there any smarter smart pointer that tracks all pointers (both raw and smart) to an object?

    No. There is no such standard pointer and such pointer is not implementable in standard C++.

    2) Is there any smarter smart pointer that at least tracks all shared_ptrs to an object?

    It is somewhat unclear what you mean. Ownership is implicitly shared with all copies of the shared pointer. If you mean that you want taking ownership with separate shared pointers to work, there is no such smart pointer in C++. Maybe implementable with a global data structure.

    On the other hand, std::enable_shared_from_this might be what you're looking for instead. It still doesn't work if you try to take shared ownership separately, but it provides a convenient way to join an existing ownership without needing access to any of the shared pointers.