The following code work and prints out Dead
. How does the call to callback_fn
not cause a crash since destructor is obviously called?
#include <iostream>
#include <memory>
#include <functional>
class A {
private:
std::string message = "Alive";
public:
~A() { message = "Dead"; }
auto get_callback() { return [this](){ callback(); }; }
private:
void callback() const { std::cout << message << std::endl; }
};
int main()
{
std::function<void()> callback_fn;
{
A a;
callback_fn = a.get_callback();
}
callback_fn();
}
Since this
is captured by value:
- How does the member function call work after object destruction?
- Why isn't the memory of
message
being freed ata
destruction?
If I write main
like this, I get no output (which I suspect to be undefined behaviour). I would expect the same behaviour as the code abve.
int main()
{
auto a = std::make_unique<A>();
auto callback_fn = a->get_callback();
a.reset();
callback_fn();
}