为什么通过shared_from_this()会导致段故障
Why passing shared_from_this() will cause segment fault?
说我们有一个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;
}
输出为:
开始...
分割故障
对我的理解,这就是正在发生的事情:
- 在main()中,
f
是一个共享的_ptr,指向foo的实例,例如ins
。 - 当调用
f->doSth()
时,ins.doSth()
实际上被称为。 - 在ins.dosth中,
this
是ins
的指针。shared_from_this()
是ins
的共享_ptr。
为什么步骤3引起段故障?
这与shared_from_this
无关。如果您在调试器中查看,则表明此segfault位于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;
});
相关文章:
- Python & C-C++ 扩展模块案例段故障
- 中断;导致段故障
- 带指针的调用函数会导致段故障
- 由于变量范围导致的段故障
- 为什么通过shared_from_this()会导致段故障
- 简单的C++字符数组加密功能 - 段故障
- std::vector的函数push_back中的堰段故障
- 位字段 keil 重新启动后硬故障
- 在openCV中将cvPoint[][]转换为cvPoint**时出现段故障
- 模板变量分配段故障11
- CIN 一个非常大的 int 数组,段故障 11
- C++段故障错误
- 段故障 -> 在标准::basic_ostream<字符中,标准::char_traits<char>
- C++中的二叉树段故障
- 调试执行工作正常,但正常的一段故障
- c++:几乎相同的输入,但第二次调用显示段故障
- 段故障。地址0x0不是堆叠的、恶意的或(最近)释放的
- 使用矢量引起的段故障
- 使用arm-linux- gnuabi -g++ -o时出现段故障,不使用-o也不会出现问题
- 为什么会出现以下段故障