boost::asio(2):shared_from_this详解
2014-05-19 17:39
155 查看
这就得从智能指针说起,智能指针就是利用一个变量的构造和析构函数来动态管理一个指针。
说白了就是:构造-->new;析构-->delete
我们可以很容易写一个智能指针:
这没有问题,很OK。
boost::asio就提供了该方法,可以迅速让shared_ptr来管理你的类。
但是这样就导致了一个问题,当你的类派生之enable_shared_from_this的时候,无法在类成员函数里面使用shared_from_this()获取类指针。
如下的用法是错误:
输出为:
B::B()
4
B::~B()
B::~B()
两次析构同一个对象,发生灾难性后果。
同样,如下的用法也是错误的:
总结如下:
1. 将该类派生之enable_shared_from_this。例如:class A : public enable_shared_from_this<A>
2. 使用的时候必须加上shared_ptr<A> abc(new A())
说白了就是:构造-->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())
相关文章推荐
- boost::enable_shared_from_this的部分实现研究
- How to get a boost::shared_ptr from this
- boost::enable_shared_from_this分析
- Boost 库 Enable_shared_from_this 实现原理分析
- boost::enable_shared_from_this分析
- BOOST enable_shared_from_this
- Boost 库 Enable_shared_from_this 实现原理分析
- boost 库 enable_shared_from_this 实现原理分析
- boost::enable_shared_from_this的部分实现研究
- Boost 库 enable_shared_from_this 实现原理分析
- 关于boost中enable_shared_from_this类的原理分析
- 对boost::shared_from_this的进一步封装
- boost 库 enable_shared_from_this 实现原理分析
- 用boost::shared_ptr和shared_from_this()时,程序崩溃
- boost::shared_from_this值得注意的地方
- boost::weak_ptr和enable_shared_from_this
- 【Boost】boost::shared_from_this值得注意的地方
- Boost 库 Enable_shared_from_this 实现原理分析
- boost 库 enable_shared_from_this 实现原理分析
- boost::shared_ptr shared_from_this