Force an object to be allocated on the heap
- by Warren Seine
A C++ class I'm writing uses shared_from_this() to return a valid boost::shared_ptr<>. Besides, I don't want to manage memory for this kind of object.
At the moment, I'm not restricting the way the user allocates the object, which causes an error if shared_from_this() is called on a stack-allocated object.
I'd like to force the object to be allocated with new and managed by a smart pointer, no matter how the user declares it. I thought it could be done through a proxy or an overloaded new operator, but I can't find a proper way of doing that.
Is there a common design pattern for such usage? If it's not possible, how can I test it at compile time?