Chinaunix首页 | 论坛 | 博客
  • 博客访问: 891995
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: C/C++

2014-10-30 14:59:33

shared_from_this()在一个类中需要传递类对象本身shared_ptr的地方使用shared_from_this函数来获得指向自身的shared_ptr,它是enable_shared_from_this的成员函数,返回shared_ptr
首先需要注意的是:这个函数仅在shared_ptr的构造函数被调用之后才能使用。原因是enable_shared_from_this::weak_ptr并不在enable_shared_from_this构造函数中设置,而是在shared_ptr的构造函数中设置。 
a) 如下代码是错误的:
  1. class D:public boost::enable_shared_from_this  
  2. {  
  3. public:  
  4.     D()  
  5.     {  
  6.         boost::shared_ptr p=shared_from_this();  
  7.     }  
  8. };  
原因很简单,在D的构造函数中虽然可以保证enable_shared_from_this的构造函数已经被调用,但正如前面所说,weak_ptr还没有设置。 
b) 如下代码也是错误的:
  1. class D:public boost::enable_shared_from_this  
  2. {  
  3. public:  
  4.     void func()  
  5.     {  
  6.         boost::shared_ptr p=shared_from_this();  
  7.     }  
  8. };  
  9. void main()  
  10. {  
  11.     D d;  
  12.     d.func();  
  13. }  
错误原因同上。 
c) 如下代码是正确的:
  1. void main()  
  2. {  
  3.     boost::shared_ptr d(new D);  
  4.     d->func();  
  5. }  
这里boost::shared_ptr d(new D)实际上执行了3个动作:
1. 首先调用enable_shared_from_this的构造函数;
2. 其次调用D的构造函数;
3. 最后调用shared_ptr的构造函数。
是第3个动作设置了enable_shared_from_this的weak_ptr,而不是第1个动作。这个地方是很违背c++常理和逻辑的,必须小心。 

结论是:不要在构造函数中使用shared_from_this;其次,如果要使用shared_ptr,则应该在所有地方均使用,不能使用D d这种方式,也决不要传递裸指针。   

Purpose

The header  defines the class template enable_shared_from_this. It is used as a base class that allows a  to the current object to be obtained from within a member function.

enable_shared_from_this defines two member functions called shared_from_this that return a shared_ptr and shared_ptr, depending on constness, to this.

Example

class Y: public enable_shared_from_this
{
public:

    shared_ptr f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr p(new Y);
    shared_ptr q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

Synopsis

namespace boost
{

template class enable_shared_from_this
{
public:

    shared_ptr shared_from_this();
    shared_ptr shared_from_this() const;
}

}

template shared_ptr enable_shared_from_this::shared_from_this();

template shared_ptr enable_shared_from_this::shared_from_this() const;

Requires: enable_shared_from_this must be an accessible base class of T*this must be a subobject of an instance t of type T . There must exist at least one shared_ptr instance p that owns t.

Returns: A shared_ptr instance r that shares ownership with p.

Postconditions: r.get() == this.



阅读(1842) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~