mardi 9 juillet 2019

How to avoid dangling pointer with shared_ptr?

I have a class whose object pointers will be added as a key/data in multiple std::map/std::unordered_map/hash(internally implemented). In order to automate deletion of the object I am using shared_ptr.

I have designed my class using shared_ptr only class.

Now I want to make sure that in future no one does this:

#include <memory>
#include <string>

class A {
 protected:
   struct this_is_private;

 public:
   explicit A(const this_is_private &) {}
   A(const this_is_private &, ::std::string, int) {}

   template <typename... T>
   static ::std::shared_ptr<A> create(T &&...args) {
      return ::std::make_shared<A>(this_is_private{0},
                                   ::std::forward<T>(args)...);
   }

 protected:
   struct this_is_private {
       explicit this_is_private(int) {}
   };

   A(const A &) = delete;
   const A &operator =(const A &) = delete;
};

::std::shared_ptr<A> foo()
{
   ::std::shared_ptr<A> temp = A::create();
   ::std::map<A*, int> m_error;
   ::std::map<::std::shared_ptr<A>, int> m_ok;
   A * obj_ptr = temp.object(); 
   m_error.insert(pair<A*, int>(obj_ptr, 10)); //How to make sure no one do this in future
   m_ok.insert(pair<::std::shared_ptr<A>, int>(temp,10)); //ok
}

Aucun commentaire:

Enregistrer un commentaire