当类对象被 shared_ptr 管理时,需要在类自己定义的函数里把当前类对象作为参数传给其他函数时,这时需要传递一个 shared_ptr ,否则就不能保持 shared_ptr 管理这个类对象的语义(因为有一个 raw pointer 指向这个类对象,而 shared_ptr 对类对象的这个引用没有计数,很有可能 shared_ptr 已经把类对象资源释放了,而那个调用函数还在使用类对象——显然,这肯定会产生错误
class B {
public:
B(): x_(4) {
cout << "B::B()" << endl;
}
~B() {
cout << "B::~B()" << endl;
}
void f() {
shared_ptr<B> p(this);
cout << p->x_ << endl;
//shared_from_this();
}
private:
int x_;
};
int main(int argc, char** argv) {
shared_ptr<B> x(new B);
x->f();
return 0;
}
运行结果:
B::B()
4
B::~B()
B::~B()
现在试一下enable_shared_from_this
class A : public enable_shared_from_this<A> {
public:
A() {
cout << "A::A()" << endl;
}
~A() {
cout << "A::~A()" << endl;
}
void f() {
//cout << shared_from_this()->x_ << endl; // this way is okay too
shared_ptr<A> p = shared_from_this();
cout << p->x_ << endl;
}
private:
int x_;
};
int main(int argc, char** argv) {
shared_ptr<A> x(new A);
x->f();
return 0;
}
运行结果:
[cpp]
A::A()
0
A::~A()
在自己的类里面访问自己的成员,其实一点必要都没有,不过有一种可能,就是f函数需要返回自己的指针给调用者
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}