Is there a way to prevent shared_from_this() call for a stack-allocated object ?
The enable_shared_from_this<> in the base classes list is a strong indicator for class user, but is there a way to enforce the correct usage ?
Example code:
class C : public enable_shared_from_this<C>
{
public:
shared_ptr<C> method() { return shared_from_this(); }
};
void func()
{
C c;
shared_ptr<C> ptr = c.method(); // exception coming from shared_from_this()
}
So to protect against this problem you can make your constructors private and only provide creation functions that return shared_ptr – this way the object can’t be allocated on the stack, like this:
If you find yourself wishing for an
operator=you can provide a clone function using a private implemented copy constructor, something like this