How below code is printing "Hello 4", I have declared test obj, and passed this obj as reference to configure method, and after obj is out of scope, I am calling obj.p1() intentionally (expecting some garbage value/Crash).
But how each time is outputting Hello 4.
Is compiler doing some kind of optimization? If yes then any pseudo code representing it is appreciated.
class sample1
{
public:
std::function<void()> p1;
void configure(std::function<void()> TCallbackFn)
{
p1 = TCallbackFn;
}
};
class test
{
public:
int a;
test(int a) : a(a)
{
}
~test()
{
}
void print() const
{
cout<<"Hello "<<a;
}
};
int main()
{
sample1 obj;
{
test t(4);
obj.configure([&]()
{
t.print();
});
}
obj.p1();
}