Search code examples
c++multithreadingshared-ptrsmart-pointersreference-counting

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?


Solution

  • 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.