zeejan
zeejan

Reputation: 285

Can pointer 'this' be a shared pointer?

I have a question about the this pointer in C++.

If I create a pointer,

std::shared_ptr<SomeClass> instance_1;

Is the this pointer of instance_1 also a shared pointer?

The reason I ask this question is, if I start another thread in its method using pointer this. Will it copy the shared_ptr?

Upvotes: 1

Views: 4721

Answers (4)

Niall
Niall

Reputation: 30614

Is the this pointer of instance_1 also a shared pointer?

No. The this pointer is the pointer to the current instance of an object, it points to the same shared object as the shared pointer in this case. But it is itself not a shared_ptr. It is of type SomeClass*.

The reason I ask this question is...

To create a shared_ptr from this, SomeClass must be derived from std::enable_shared_from_this. Then you can use;

shared_from_this(); returns a shared_ptr which shares ownership of *this

When sharing state like this between threads, be careful of race conditions and locking issues etc.

Upvotes: 3

Slava
Slava

Reputation: 44268

No, you cannot make this to be a shared pointer. Closest thing is to inherit from std::enable_shared_from_this and get shared pointer by calling:

this->shared_from_this();

details can be found here

Another alternative would be to use intrusive shared pointer, like boost::intrusive_ptr, where this will not be shared pointer though but can be converted to one.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490573

No. Creating a shared pointer to an object does not make this in the object a shared pointer.

If you want to get a shared pointer from this, you might want to at least consider using std::enable_shared_from_this.

Upvotes: 2

0x5453
0x5453

Reputation: 13599

No, this is always a raw pointer. If you want another thread to have a copy of the shared_ptr, you will have to give it instance_1.

Upvotes: 0

Related Questions