假设我们有一个Foo类定义如下:
// foo.hpp
class Foo;
using FooCallback = std::function<void(std::shared_ptr<Foo> ins)>;
class Foo : public std::enable_shared_from_this<Foo>{
public:
Foo(int b, const FooCallback& callback):m_bar(b),
m_callback(callback){}
int
getBar();
void
doSth();
private:
int m_bar;
const FooCallback& m_callback;
};
为什么以下代码会导致段错误?
// foo.cpp
#include "foo.hpp"
int
Foo::getBar(){
return m_bar;
}
void
Foo::doSth(){
std::cout << "Start ... " << std::endl;
this->m_callback(shared_from_this());
std::cout << "End ... " << std::endl;
}
int main()
{
auto f = std::make_shared<Foo>(100,
[](std::shared_ptr<Foo> ins){
std::cout << "bar: " << ins->getBar() << std::endl;
});
f->doSth();
return 0;
}
输出结果为:
开始......
分段错误
根据我的理解,这是正在发生的事情:
f
是指向Foo实例的shared_ptr,比如它是ins
。 f->doSth()
时,实际上会调用ins.doSth()
。 this
是指向ins
的指针。 shared_from_this()
是ins
的shared_ptr。 那么为什么步骤3导致段故障?
答案 0 :(得分:3)
这与shared_from_this
无关。如果您查看调试器,它会在std::function
的内部指针所指向的位置显示此段错误。
这是因为m_callback
是一个引用,当你调用doSth
时,它引用的函数对象不再存在(因为它是一个临时对象)。
要解决此问题,您可以按值保存m_callback
:
const FooCallback m_callback;
甚至更好,因为lambda没有捕获任何东西,你可以使m_callback
成为普通函数引用(或指针):
using FooCallback = void(std::shared_ptr<Foo> ins);
…
FooCallback& m_callback;
…
auto f = std::make_shared<Foo>(100,
*[](std::shared_ptr<Foo> ins){
std::cout << "bar: " << ins->getBar() << std::endl;
});