Search code examples
c++c++11c++14shared-ptrsmart-pointers

Tracking down owner of a shared_ptr?


In our app we're about to (finally..) switch from raw pointers to using C++11 smart_ptr templates.

We do have the occasional bug in our app with (non C++) objects still keeping references to our C++ objects causing crashes in the past when accessing the then-dealloc'd objects.

Not sure if this is a silly question - but is there a way to take advantage of the smart_ptr objects and 'dump' the objects still holding on to the C++ objects when none are expected to hold a reference to one any more?

I guess what I'm asking for is a way to list all owners of smart_ptr<MyClass> at a certain point in time.

Any suggestions much appreciated!


Solution

  • No. Without creating your own smart pointer classes that wrap std::unique_ptr and std::shared_ptr (ignore the deprecated std::auto_ptr) that tracks this information, there is no way to do that. The standard classes themself do not track this information (would be too costly).

    Another alternative would be to modify the code of your standard library implementation to track that info. Less invasive on your code since you can keep using the standard names. But probably a bit more tricky than just wrapping the classes and use the wrappers.