ryan0270
ryan0270

Reputation: 1217

Count number of shared_ptr in existence

I have a data class where I usually pass objects of this class around using shared_ptr. Now I'd like to try keep track of how many shared_ptr's exist to objects of that class. Note that this is not the same as how many pointers there are to a specific object. Primarily I want this to help identify possible memory leaks but also there are situations where knowing the actual number is useful.

One idea I had was to keep a static list of weak pointers to every shared_ptr constructed. I could then periodically check to see how many of the weak pointers are still valid. The problem here is, how do I automatically add a weak pointer to the list every time a shared_ptr is created? Will a custom allocator work?

Does anyone know of a reasonable way to do this?

Upvotes: 1

Views: 137

Answers (1)

woolstar
woolstar

Reputation: 5083

You'll need to create a wrapper or factory where you get all your shared_ptr, so that at the same time, you can do your side accounting.

template<class T, class... Args>
  typename std::shared_ptr<T> make_recorded(Args... ar)
  { 
    std::shared_ptr<T> ptr= make_shared<T>(ar) ;
    // add your annotation/tracking here
    return ptr ;
  } 

Upvotes: 3

Related Questions