我试图追捕为什么一个程序崩溃在shared_ptr
。为什么我的程序在boost :: enable_shared_from_this <>/boost :: shared_ptr <>中崩溃?
#0 0x00007fff90723212 in __pthread_kill()
#1 0x00007fff93415b54 in pthread_kill()
#2 0x00007fff93459dce in abort()
#3 0x00007fff8a0519eb in abort_message()
#4 0x00007fff8a04f39a in default_terminate()
#5 0x00007fff930bf887 in _objc_terminate()
#6 0x00007fff8a04f3c9 in safe_handler_caller()
#7 0x00007fff8a04f424 in std::terminate()
#8 0x00007fff8a05058b in __cxa_throw()
#9 0x0000000100057cbc in boost::throw_exception<boost::bad_weak_ptr> ([email protected]) at throw_exception.hpp:66
#10 0x0000000100057bf4 in boost::detail::shared_count::shared_count (this=0x1002c5d00, [email protected]) at shared_count.hpp:509
#11 0x0000000100057b7d in boost::detail::shared_count::shared_count (this=0x1002c5d00, [email protected]) at shared_count.hpp:511
#12 0x000000010004ad14 in boost::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass>::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass> (this=0x1002c5cf8, [email protected]) at shared_ptr.hpp:220
#13 0x000000010004acad in boost::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass>::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass> (this=0x1002c5cf8, [email protected]) at shared_ptr.hpp:223
#14 0x000000010004a9b4 in boost::enable_shared_from_this<myns::(anonymous namespace)::MySharedFromThisClass>::shared_from_this (this=0x100304178) at enable_shared_from_this.hpp:49
MySharedFromThisClass定义为:
class MySharedFromThis : public boost::enable_shared_from_this<MySharedFromThis> {
// ....
};
而这是正在传递的实例的定义,如:
auto myKlass = std::make_shared<MySharedFromThis>();
而经由围绕复制:
void myFunction(::boost::shared_ptr<MySharedFromThis> myKlass) {
myFunction(shared_from_this());
}
什么原因呢?没有任何警告或错误的东西编译,但事情非常清楚地以不愉快的方式进行段错误。
ABI在这里不是问题。正如预期的那样,您只会得到'bad_weak_ptr'异常,但不要捕获它,所以线程(和进程)终止。 – 2013-04-10 07:56:42
使用'enable_shared_from_this <>'被调用'shared_form_this()'这个异常的对象的构造函数的一个常见原因被共享 - 不是一种罕见的事情,如果你想传递一个指向对象到其聚集的构造成员。整洁的解决办法是宣布你的构造私人和提供工厂方法,在其中您可以用'shared_form_this()'同性恋放弃。 – marko 2013-04-10 14:18:15