Tracking shared_ptr owner?

In our application, we are going to (finally ..) switch from source pointers to using C ++ 11 templates smart_ptr.

We have a random error in our application with (non-C ++) objects still storing references to our C ++ objects, causing crashes in the past when accessing then-dealloc'd objects.

Not sure if this is a stupid question, but is there a way to use objects smart_ptrand 'dump' objects that still hold C ++ objects when none of them contain a link to one of them anymore?

I suggest that I ask to describe all the ownerssmart_ptr<MyClass> at a particular point in time.

Any suggestions that were highly appreciated!

+4
source share
3 answers

No. Without creating your own smart pointer classes that wrap std::unique_ptrand std::shared_ptr(ignore obsolete std::auto_ptr) that track this information, there is no way to do this. Standard classes themselves do not track this information (it would be too expensive).

Another alternative would be to modify the code for a standard library implementation to track this information. Less invasive code as you can continue to use standard names. But probably a little more complicated than just wrapping classes and using wrappers.

+1
source

, - ++. shared_ptr .

template<typename T>
class mySmartPtr : boost::noncopyable{
    public:
         // This method should be the only way this object can be copied
         // as the copy constructors are made private
         // The newOwnerName parameter can be used to populate m_onwers.
         static mySmartPtr<T> newOwner(mySmartPtr<T>&, std::string newOnwerName); 
    private:
         std::shared_ptr<T> m_ptr;
         static std::vector<std::string> m_owners;
};
0

( ++) , ++, then-dealloc'd.

.

, , .

3 :

  • ( )

  • ( 1, )

  • , , , .

shared_ptr, , shared_ptr . "", :

  • , shared_ptr
  • shared_ptr, .

, . .

0

Source: https://habr.com/ru/post/1648945/


All Articles