我对 C++ 中的 this
指针有疑问。
如果我创建一个指针,
std::shared_ptr<SomeClass> instance_1;
instance_1
的this
指针也是共享指针吗?
我问这个问题的原因是,如果我使用指针 this
在其方法中启动另一个线程。它会复制 shared_ptr
吗?
最佳答案
Is the
this
pointer ofinstance_1
also a shared pointer?
没有。 this
指针是指向对象当前实例的指针,在本例中它指向与共享指针相同的共享对象。但它本身不是 shared_ptr
。它的类型是 SomeClass*
。
The reason I ask this question is...
要从 this
创建一个 shared_ptr
,SomeClass
必须派生自 std::enable_shared_from_this
.然后就可以使用了;
shared_from_this()
; returns ashared_ptr
which shares ownership of*this
当在线程之间共享这样的状态时,要注意竞争条件和锁定问题等。
关于c++ - 指针 'this' 可以是共享指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598634/