这就得从智能指针说起,智能指针就是利用一个变量的构造和析构函数来动态管理一个指针。
说白了就是:构造-->new;析构-->delete
我们可以很容易写一个智能指针:
template <class T>
class TAutoPtr
{
public:
TAutoPtr() {
m_t = new T();
cout << "TAutoPtr::TAutoPtr()" << endl;
}
~TAutoPtr() {
delete m_t;
cout << "TAutoPtr::~TAutoPtr()" << endl;
}
private:
T* m_t;
};
使用:
int main(int argc, char** argv)
{
TAutoPtr<int> tt;
return 0;
}这没有问题,很OK。
boost::asio就提供了该方法,可以迅速让shared_ptr来管理你的类。
但是这样就导致了一个问题,当你的类派生之enable_shared_from_this的时候,无法在类成员函数里面使用shared_from_this()获取类指针。
如下的用法是错误:
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;
}
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()
两次析构同一个对象,发生灾难性后果。
同样,如下的用法也是错误的:
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_from_this();
//shared_ptr<A> p = shared_from_this();
//cout << p->x_ << endl;
}
private:
int x_;
};
int main(int argc, char** argv)
{
A* aa = new A();
aa->f();
return 0;
}
虽然我们已经将类A派生之enable_shared_from_this,但是我们使用的时候并没有用shared_ptr<A>包装类A。也错误。
总结如下:
1. 将该类派生之enable_shared_from_this。例如:class A : public enable_shared_from_this<A>
2. 使用的时候必须加上shared_ptr<A> abc(new A())
本文介绍了如何使用智能指针管理动态分配的对象,并探讨了在类中使用enable_shared_from_this时可能出现的问题及正确实践。
194

被折叠的 条评论
为什么被折叠?



