C++11 Passing 'this' as paramenter for std::make_shared
Asked Answered
P

1

15

I'm 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 I can properly pass this as an argument?

Pitzer answered 10/5, 2012 at 12:40 Comment(1)
"does not work properly" - why not? what happens? why is that bad? please describe problems in non-generalities, so that future readers can find them with search terms.Pal
S
19

I think what you probably want here is shared_from_this.

// 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 comments from David Rodriguez:

Note that shared_from_this() should never be called on an object that isn't already managed by a shared_ptr. This is valid:

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

While the following leads to undefined behaviour (attempting to call delete on a):

A a;
a.createB();
Singlephase answered 10/5, 2012 at 12:44 Comment(2)
It is important to note that shared_from_this() requires that the current object is already managed in a shared_ptr. I.e. int main() { A a; a.createB(); } is undefined behavior, while int main() { shared_ptr<A> a( new A ); a->createB(); } is correct.Quadrumanous
@DavidRodríguez-dribeas Absolutely. I've updated the answer accordingly. Thanks.Singlephase

© 2022 - 2024 — McMap. All rights reserved.