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::map<A*, int> m_error; ::std::map<::std::shared_ptr<A>, int> m_ok; ::std::shared_ptr<A> foo() { ::std::shared_ptr<A> temp = A::create(); A * obj_ptr = temp.get(); 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 }
Awithout using yourcreatefunction. If someone really wants to shoot themselves in the foot, you can't stop them.make_uniqueandmake_sharedwhen creating pointers.shared_ptr<A>stored internally. But ultimately people could take/store pointers of that too. Not to mention that you could just as easily store references toA(by just dereferencing ashared_ptr<A>) which is even more impossible to avoid.deletetheoperator&for your class to prevent anyone from taking its addresses the simple way, but there's alsostd::addressofand, of course,std::shared_ptr<A>::get(and like 10 more ways) that you can't possibly prevent. godbolt.org/z/vDw801