Say we have a class Foo defined as follows:
// 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;
};
Why will the following code cause segment fault?
// 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;
}
The output is:
Start ...
segmentation fault
To my understanding, this is what is going on:
- In main(),
f
is a shared_ptr pointing to an instance of Foo, say it'sins
. - When
f->doSth()
is called,ins.doSth()
is actually called. - In ins.doSth,
this
is a pointer toins
. Andshared_from_this()
is a shared_ptr toins
.
So why is step 3 causing the segment fault?