我正在试图找出一个程序在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> (e=@0x1002c5b88) at throw_exception.hpp:66
#10 0x0000000100057bf4 in boost::detail::shared_count::shared_count (this=0x1002c5d00, r=@0x100304180) at shared_count.hpp:509
#11 0x0000000100057b7d in boost::detail::shared_count::shared_count (this=0x1002c5d00, r=@0x100304180) at shared_count.hpp:511
#12 0x000000010004ad14 in boost::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass>::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass> (this=0x1002c5cf8, r=@0x100304178) at shared_ptr.hpp:220
#13 0x000000010004acad in boost::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass>::shared_ptr<myns::(anonymous namespace)::MySharedFromThisClass> (this=0x1002c5cf8, r=@0x100304178) 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());
}
一切编译都没有警告或错误,但很明显有不太愉快的崩溃。
bad_weak_ptr
异常 - 但不要捕获它,这样线程(和进程)就会终止。 - Igor R.enable_shared_from_this <>
引起此异常的常见原因是在被共享的对象的构造函数中调用shared_form_this()
- 如果您想将指针传递给其聚合成员的构造函数,则这不是罕见的事情。 简洁的解决方案是声明您的构造函数为私有并提供工厂方法,在其中可以毫不犹豫地使用shared_form_this()
。 - marko