Enable_shared_from_this and objects on the stack

What about calling shared_from_this for objects with a selected glass? is enable_shared_from_thom in the list of base classes an indicator for a user of a derived class to create it only on the heap (and we just hope that the class is used correctly) or can we have stronger protection against such errors? Or do I not understand some points?

Code example:

 class C : public enable_shared_from_this<C> { public: shared_ptr<C> method() { shared_from_this(); } }; 

void func () {C c; shared_ptr <C> ptr = c.method (); // exception comming from shared_from_this ()}

+6
c ++ boost smart-pointers
source share
1 answer

So, to protect this problem, you can make your counterstructures private and provide only creation functions that return shared_ptr - this way, the object cannot be allocated on the stack, for example:

 class C : public enable_shared_from_this<C> { public: static shared_ptr<C> create() { return shared_ptr<C>(new C() ); } shared_ptr<C> method() { shared_from_this(); } private: C() {...} // Make operator= and C(const C&) private unimplemented // so the used cant do bad things like C c( * c_ptr ); C& operator=( const C & ); C( const C & ); }; void func() { C c; // This doesnt compile shared_ptr<C> ptr = c.method(); // So you can never get this } void altfunc() { shared_ptr<C> c_ptr = C::create(); C & c_ref = *c; shared_ptr<C> ptr = c_ref.method(); // OK } 

If you want an anonymizer = you can provide a clone function using a private implemented copy constructor, something like this

 // This goes in class C shared_ptr<C> C::clone() const { return shared_ptr<C>( new C(*this) ); } // This is how you can use it shared_ptr<C> c2 = c1->clone(); 
+10
source share

All Articles