I’m working on C++ framework and would like to apply automatic memory management to a number of core classes. So far, I have the standard approach which is
class Foo { public: static shared_ptr<Foo> init() { return shared_ptr<Foo>(new Foo); } ~Foo() { } protected: Foo() { } }; // Example of use shared_ptr<Foo> f = Foo::init();
However, the above breaks when I subclass Foo, since even tho init() is inherited, it still returns shared_ptr<Foo> which contains a pointer to instance of Foo.
Can anyone think of an elegant solution to this? Should I perhaps just stick with (semi-)manually wrapping instances of class with shared_ptr? This would also give ability to expose parameterized constructors without declaring new named constructors…
Ie.
template <typename T> shared_ptr<T> make_shared(T* ptr) { return shared_ptr<T>(ptr) } // Example shared_ptr<T> f1 = make_shared(new Foo()), f2 = make_shared(new Foo(1,2));
I don’t understand what this achieves, you don’t appear to be getting any extra memory management using this init function than by simply declaring a shared_ptr.
What’s the difference. shared_ptr provides the memory management, not anything in init.