0

I was trying some things with references and pointers, and I found something that I do not understand at all.

Here is my code:

#include <iostream>

using namespace std;

class A
{
    public:
     A() { cout << "con\n"; }
    ~A() { cout << "des\n"; }

    void f() { cout << "bla" << endl; }
};

A &createA()
{
    A *a = nullptr;

    {
        A b;
        a = &b;
        cout << *&a << endl;
    }

    return *a;
}

int main()
{
    A &b(createA());
    cout << &b << endl;

    b.f();

    system("pause");

    return 0;
}

The output:

con
des
0058FE0B
0058FE0B
bla
Press any key to continue . . .

As you can see the member function f() still gets called, even after the object itself has been destroyed. Why? I thought there should be some error, but the function f() does get called and it event does everything correctly, why?

DasOhmoff San
  • 865
  • 6
  • 19

2 Answers2

2

Compiler warnings are pretty self-explanatory here:

main.cpp: In function 'A& createA()':
main.cpp:24:13: warning: function may return address of local variable [-Wreturn-local-addr]
     return *a;
             ^
main.cpp:19:11: note: declared here
         A b;
           ^
georgeliatsos
  • 1,168
  • 3
  • 15
  • 34
2

This is undefined behaviour, plain and simple.

The compiler is not required to warn you when you engage in UB, but it is allowed to assume you won't do that and if you do it anyway you have no guarantees about what will happen. The program is simply invalid and anything could happen.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70