是否可以删除对自身的 shared_ptr 引用
Is it OK to remove shared_ptr reference to itself
删除方法中对自身的唯一 shared_ptr 引用是否安全?像下面这样的东西。如果两个对象,一个 class A 和另一个 class B,通过它们的 pB_
和 pA_
指向彼此。假设pB_
是对classB对象的唯一引用,那么我在classA
的对象上调用A::method()
。会不会有什么问题?
#include <iostream>
using std::shared_ptr
class B;
class A {
public:
void method() {
pB_->method();
}
shared_ptr<B> pB_;
};
class B {
public:
void method() {
pA_->pB_.reset();
// Is this OK? And is it safe if I don't do this?
some_other_data_ = 10;
}
shared_ptr<A> pA_;
int some_other_data_;
};
重置该指针将导致 B
对象被删除,所以不,在该点之后访问其成员之一是不正确的。有关详细信息,请参阅:Is it safe to `delete this`?
删除方法中对自身的唯一 shared_ptr 引用是否安全?像下面这样的东西。如果两个对象,一个 class A 和另一个 class B,通过它们的 pB_
和 pA_
指向彼此。假设pB_
是对classB对象的唯一引用,那么我在classA
的对象上调用A::method()
。会不会有什么问题?
#include <iostream>
using std::shared_ptr
class B;
class A {
public:
void method() {
pB_->method();
}
shared_ptr<B> pB_;
};
class B {
public:
void method() {
pA_->pB_.reset();
// Is this OK? And is it safe if I don't do this?
some_other_data_ = 10;
}
shared_ptr<A> pA_;
int some_other_data_;
};
重置该指针将导致 B
对象被删除,所以不,在该点之后访问其成员之一是不正确的。有关详细信息,请参阅:Is it safe to `delete this`?