C ++ 11 Passing 'this' as an argument to std :: make_shared

I am trying to pass 'this' to the constructor using std :: make_shared

Example:

// headers class A { public: std::shared_ptr<B> createB(); } class B { private: std::shared_ptr<A> a; public: B(std::shared_ptr<A>); } // source std::shared_ptr<B> A::createB() { auto b = std::make_shared<B>(this); // Compiler error (VS11 Beta) auto b = std::make_shared<B>(std::shared_ptr<A>(this)); // No compiler error, but doenst work return b; } 

However, this does not work properly, any suggestions, how can I correctly pass this as an argument?

+7
source share
1 answer

I think you probably want shared_from_this here.

 // headers class A : std::enable_shared_from_this< A > { public: std::shared_ptr<B> createB(); } class B { private: std::shared_ptr<A> a; public: B(std::shared_ptr<A>); } // source std::shared_ptr<B> A::createB() { return std::make_shared<B>( shared_from_this() ); } 

Update to include David Rodriguez's comments :

Note that shared_from_this() never needs to call an object that is not yet managed by shared_ptr . It's really:

 shared_ptr<A> a( new A ); a->createB(); 

While the following leads to undefined behavior (trying to call delete on a ):

 A a; a.createB(); 
+13
source

All Articles