2013-04-10 87 views
3

我试图追捕为什么一个程序崩溃在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()); 
} 

什么原因呢?没有任何警告或错误的东西编译,但事情非常清楚地以不愉快的方式进行段错误。

回答

4

我发布了我自己的答案,因为这段代码编译时没有任何警告或错误,并花费相当多的精力追查。

应该基于在这条线的时候看上面的例子是相当明显的:

auto myKlass = std::make_shared<MySharedFromThis>(); 

myKlass的类型std::shared_ptr<MySharedFromThis>,不boost::shared_ptr<MySharedFromThis>的。将std::make_shared<>更改为boost::make_shared<>,并且一切按预期/预期工作。

有两种可能的事情导致这种崩溃:

  1. 在myFunction的到shared_from_this()()的调用是被称为没有现成::boost::shared_ptr<>已经存在。相反,发生了什么是std::shared_ptr<>被创建,其具有不同的ABI,即boost::shared_ptr<>。值得注意的是libboost_thread-mt.dylib预计boost::enable_shared_from_this<>类,而不是std::enable_shared_from_this<>类。
  2. 根据enable_shared_from_this<> documentation,前提条件未得到满足。

    要求:enable_shared_from_this必须是一个可访问的基类T. *这必须是类型T的实例t的子对象。必须至少存在一个拥有t的shared_ptr实例p。

    而是发生了什么事情是有一个std::shared_ptr<>实例,但不是boost::shared_ptr<>实例。

至少这是我发生了什么事情的理解。我觉得#1是导致段错误的现实问题,并#2将是一个问题迟早(虽然我并不完全相信)。

+1

ABI在这里不是问题。正如预期的那样,您只会得到'bad_weak_ptr'异常,但不要捕获它,所以线程(和进程)终止。 – 2013-04-10 07:56:42

+1

使用'enable_shared_from_this <>'被调用'shared_form_this()'这个异常的对象的构造函数的一个常见原因被共享 - 不是一种罕见的事情,如果你想传递一个指向对象到其聚集的构造成员。整洁的解决办法是宣布你的构造私人和提供工厂方法,在其中您可以用'shared_form_this()'同性恋放弃。 – marko 2013-04-10 14:18:15

相关问题