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