问题描述
我使用升压转换器的共享指针,和 enable_shared_from_this
启用共享指针返回到这一点。 code是这样的:
I'm using boost's shared pointers, and enable_shared_from_this
to enable returning a shared pointer to this. Code looks like this:
class foo : public boost::enable_shared_from_this<foo>
{
boost::shared_ptr<foo> get()
{
return shared_from_this();
}
}
为什么会shared_from_this抛出一个异常weak_ptr_cast?
Why would shared_from_this throw a weak_ptr_cast exception?
推荐答案
如果你宣布在栈上富,所以没有其他共享指针到foo。例如:
If you declared foo on the stack, so that there are no other shared pointers to foo. For example:
void bar()
{
foo fooby;
fooby.get();
}
fooby.get()抛出了 weak_ptr_cast
例外。
要解决这个问题,声明 fooby
堆:
To get around this, declare fooby
on the heap:
void bar()
{
boost::shared_ptr<foo> pFooby = boost::shared_ptr<foo>(new foo());
pFooby->get();
}
另一种可能是你正在尝试使用 shared_from_this
构造完成前,这将再次尝试返回一个共享指针不存在。
Another possibility is that you're trying to use shared_from_this
before the constructor is done, which would again try to return a shared pointer that doesn't exist yet.
这篇关于在shared_from_this提振weak_ptr_cast()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!