boost shared_from_this()中的weak_ptr_cast [英] boost weak_ptr_cast in shared_from_this()
问题描述
我使用boost的共享指针,并且 enable_shared_from_this
可以返回一个共享指针。代码如下:
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.get() would throw the weak_ptr_cast
exception.
为了解决这个问题,在堆上声明 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.
这篇关于boost shared_from_this()中的weak_ptr_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!