【发布时间】:2011-06-13 09:26:47
【问题描述】:
在我的代码中,我使用 boost::threads 并且我有一个类通过名为 fnThread() 的成员函数运行线程。在这个 fnThread() 中,我想创建一个 shared_from_this() 并将其传递给带有信号的监听方。但是boost::shared_ptr<foo> p = shared_from_this()这行抛出异常如下;
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> > at memory location 0x04c2f720.
有问题的命令是 shared_from_this() 。从另一个线程创建shared_from_this() 是非法的还是我做错了什么?任何帮助表示赞赏。谢谢!
PS:我计划将信号参数更改为普通指针,因为它不会影响我的结构。但我赞成 shared_ptr 并且我想听听任何关于这个决定的 cmets。对于这种特殊情况,也许这是一个糟糕的选择。你有什么建议?
编辑:
这里有一个简单的类供你测试
class foo : public boost::enable_shared_from_this<foo>
{
public:
int start()
{
foo_thread.reset(new boost::thread(boost::bind(&foo::fn_foo_thread, this)));
return 0;
}
~foo()
{
if (foo_thread->joinable())
foo_thread->join();
}
private:
boost::scoped_ptr<boost::thread> foo_thread;
void fn_foo_thread()
{
boost::shared_ptr<foo> p = shared_from_this();
std::cout << "foo thread terminated. \n" << std::endl;
}
};
【问题讨论】:
-
你是什么意思,“创建一个
shared_from_this()?” -
我的意思是让 'boost::shared_ptr
' 变成 'this' -
请向我们展示实例化
foo并调用start的代码。错误可能就在那里。 -
我找到了错误的根源。在一个函数中,我从一个双端队列“弹出”对象并调用它的 start 方法。一旦函数返回,该对象的唯一实例就会超出范围,但线程会继续运行并在尝试获取“shared_from_this()”时崩溃。愚蠢的错误......
标签: c++ multithreading shared-ptr boost-thread