1

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?

Niall
  • 30,036
  • 10
  • 99
  • 142
zeejan
  • 265
  • 1
  • 4
  • 10
  • 2
    `this` is always a raw pointer. But your class can derive from `std::enable_shared_from_this` to allow its methods to return a `shared_ptr` of `this` – KABoissonneault Jun 02 '16 at 17:40
  • 2
    No. But see [`std::enable_shared_from_this`](http://stackoverflow.com/a/11711094/751579). – davidbak Jun 02 '16 at 17:40
  • 1
    Possible duplicate of [how to return shared\_ptr to current object from inside the "this" object itself](http://stackoverflow.com/questions/36863240/how-to-return-shared-ptr-to-current-object-from-inside-the-this-object-itself) – davidbak Jun 02 '16 at 17:45

4 Answers4

3

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.

Niall
  • 30,036
  • 10
  • 99
  • 142
2

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.

Slava
  • 43,454
  • 1
  • 47
  • 90
2

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

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.

0x5453
  • 12,753
  • 1
  • 32
  • 61