【Boost】boost::shared_from_this值得注意的地方
来源:互联网 发布:同花顺软件购买 编辑:程序博客网 时间:2024/05/01 21:25
shared_from_this()在一个类中需要传递类对象本身shared_ptr的地方使用shared_from_this函数来获得指向自身的shared_ptr,它是enable_shared_from_this<T>的成员函数,返回shared_ptr<T>。
首先需要注意的是:这个函数仅在shared_ptr<T>的构造函数被调用之后才能使用。原因是enable_shared_from_this::weak_ptr并不在enable_shared_from_this<T>构造函数中设置,而是在shared_ptr<T>的构造函数中设置。
a) 如下代码是错误的:
b) 如下代码也是错误的:
c) 如下代码是正确的:
1. 首先调用enable_shared_from_this<D>的构造函数;
2. 其次调用D的构造函数;
3. 最后调用shared_ptr<D>的构造函数。
是第3个动作设置了enable_shared_from_this<D>的weak_ptr,而不是第1个动作。这个地方是很违背c++常理和逻辑的,必须小心。
结论是:不要在构造函数中使用shared_from_this;其次,如果要使用shared_ptr,则应该在所有地方均使用,不能使用D d这种方式,也决不要传递裸指针。
首先需要注意的是:这个函数仅在shared_ptr<T>的构造函数被调用之后才能使用。原因是enable_shared_from_this::weak_ptr并不在enable_shared_from_this<T>构造函数中设置,而是在shared_ptr<T>的构造函数中设置。
a) 如下代码是错误的:
class D:public boost::enable_shared_from_this<D>{public: D() { boost::shared_ptr<D> p=shared_from_this(); }};原因很简单,在D的构造函数中虽然可以保证enable_shared_from_this<D>的构造函数已经被调用,但正如前面所说,weak_ptr还没有设置。
b) 如下代码也是错误的:
class D:public boost::enable_shared_from_this<D>{public: void func() { boost::shared_ptr<D> p=shared_from_this(); }};void main(){ D d; d.func();}错误原因同上。
c) 如下代码是正确的:
void main(){ boost::shared_ptr<D> d(new D); d->func();}这里boost::shared_ptr<D> d(new D)实际上执行了3个动作:
1. 首先调用enable_shared_from_this<D>的构造函数;
2. 其次调用D的构造函数;
3. 最后调用shared_ptr<D>的构造函数。
是第3个动作设置了enable_shared_from_this<D>的weak_ptr,而不是第1个动作。这个地方是很违背c++常理和逻辑的,必须小心。
结论是:不要在构造函数中使用shared_from_this;其次,如果要使用shared_ptr,则应该在所有地方均使用,不能使用D d这种方式,也决不要传递裸指针。
- 【Boost】boost::shared_from_this值得注意的地方
- 【Boost】boost::shared_from_this值得注意的地方
- 【Boost】boost::shared_from_this值得注意的地方
- boost::shared_from_this值得注意的地方
- boost::shared_from_this值得注意的地方
- shared_from_this 几个值得注意的地方
- shared_from_this 几个值得注意的地方
- shared_from_this 几个值得注意的地方
- shared_from_this 几个值得注意的地方
- boost::asio要注意的一个地方
- Boost.shared_ptr必须注意的一些地方
- Boost.shared_ptr必须注意的一些地方
- Boost.shared_ptr必须注意的一些地方
- boost::shared_ptr shared_from_this
- boost库 shared_from_this
- 值得注意的地方
- 使用boost::asio需要注意的一个地方
- boost::split提取字符串需要注意的地方
- iOS的影片播放 MediaPlayer 和 AVPlayer
- qtp基础代码
- Javascript基础-Function基础
- IOS 中通过URL Schemes让一个应用程序启动另一个指定应用程序
- android 源码下载错误: [Errno 110] Connection timed out
- 【Boost】boost::shared_from_this值得注意的地方
- 二维码的生成与解析示例 生成二维码
- respondsToSelector判断是否实现了某方法
- 无法生成dump的问题
- iText制作表格比较好的文章
- Android: Ubuntu 12.04 LTS下Build Android Source Tree 4.0.1遇到的错误
- Gson简要使用笔记
- Java encoding
- 【P2P网络】Extension for Peers to Send Metadata Files翻译稿