
On 07/24/2014 06:53 AM, Gavin Lambert wrote:
1. shared_from_this can't be used from the constructor (requiring factory-method-init shenanigans); reportedly
If you are using C++11, then your factory can be made generic by using perfect forwarding: class my_class : enable_shared_from_this<my_class> { public: template <typename... Types> static std::shared_ptr<my_class> create(Types&&... args) { std::shared_ptr<my_class> self (new my_class{std::forward<Types>(args)...}); self->init(std::forward<Types>(args)...); return self; } private: my_class(); init(); }; In the above, there must be an init() function for each constructor.
And it should be possible to obtain that weak_ptr before any shared_ptr exists, and "fix" it later to point at the real shared_ptr, especially if it is known that the weak_ptr will never actually be used until that real shared_ptr exists.
This sounds a bit risky if the last assumption does not hold.