0

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();
}
  • *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash"*. **Don't expect anything from a program with UB**. – Jason Sep 22 '22 at 16:59
  • UB is UB, anything can happens, even seems to work. – Jarod42 Sep 22 '22 at 16:59
  • how you can tell the difference between a "good" 4 and a "garbage" 4 ? – 463035818_is_not_an_ai Sep 22 '22 at 16:59
  • You mean how does the undefined behaviour work? I could imagine that there's still a stale 4 in the area beyond the top of the stack or in heap memory. If other function calls that made deep use of the stack or heap were made before `obj.p1()` it could very well wipe out that part of the stack or heap where the 4 was. Anything could be happening though. You have a reference to something that is gone - that's a no-no. – Wyck Sep 22 '22 at 17:05

0 Answers0