boost::shared_from_this值得注意的地方

来源:互联网 发布:国外优秀插画师 知乎 编辑:程序博客网 时间:2024/05/02 04:29
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) 如下代码是错误的:
[cpp] view plaincopyprint?
  1. class D:public boost::enable_shared_from_this<D>  
  2. {  
  3. public:  
  4.     D()  
  5.     {  
  6.         boost::shared_ptr<D> p=shared_from_this();  
  7.     }  
  8. };  
原因很简单,在D的构造函数中虽然可以保证enable_shared_from_this<D>的构造函数已经被调用,但正如前面所说,weak_ptr还没有设置。 
b) 如下代码也是错误的:
[cpp] view plaincopyprint?
  1. class D:public boost::enable_shared_from_this<D>  
  2. {  
  3. public:  
  4.     void func()  
  5.     {  
  6.         boost::shared_ptr<D> p=shared_from_this();  
  7.     }  
  8. };  
  9. void main()  
  10. {  
  11.     D d;  
  12.     d.func();  
  13. }  
错误原因同上。 
c) 如下代码是正确的:
[cpp] view plaincopyprint?
  1. void main()  
  2. {  
  3.     boost::shared_ptr<D> d(new D);  
  4.     d->func();  
  5. }  
这里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这种方式,也决不要传递裸指针。