tommy

It's hard to tell the world we live in is either a reality or a dream
posts - 52, comments - 17, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

关于 shared_from_this 的一个要点

Posted on 2011-03-24 23:29 Tommy Liang 阅读(998) 评论(0)  编辑 收藏 引用 所属分类: C++语言与规范
不能在构造函数中使用 shared_from_this,正确的做法如下:google自: http://boost.2283326.n4.nabble.com/enabled-shared-from-this-bad-weak-ptr-exception-online-doc-explanation-td2583370.html

Since in the current version you cannot call shared_from_this() in a 
constructor, you can't initialize your members with an expression that 
invloves shared_from_this(). Instead, you can set your shared_ptr's in 
some initializing member function that would be called after the 
object is constructed: 

struct B; 
struct A 
{ 
  A(shared_ptr<B> b) 
  { 
    //... 
  } 
}; 

class B : public enable_shared_from_this<B> 
{ 
  shared_ptr<A> a_; 
public: 
  void init() 
  { 
    a_.reset(new A(shared_from_this())); 
  } 
}; 

main() 
{ 
  shared_ptr<B> b(new B); 
  b->init(); 
} 

...also you can wrap initialization in a static constructing function: 

class B.... 
{ 
  // like in the previous example 
  B() 
  {} 
public: 
  static shared_ptr<B> create() 
  { 
    shared_ptr<B> result(new B()); 
    result->init(); 
    return result; 
  } 
}; 

main() 
{ 
  shared_ptr<B> b(B::create()); 
} 

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理