1
   class fu
{
public:
    int pub;
    fu() { pub = 1; }

    ~fu() {
        std::cout << pub << "end"<<std::endl;
    }
};
fu& fub() {
    fu a;
    fu& re = a;
    return a;
}
int main() {
    std::cout << ++fub().pub;
}

output : 1 end \n 2

I expected that the reference would make an error because the variable in the function has been terminated. However, the destructor was called in and main function worked. What does the reference point to?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
park
  • 31
  • 3
  • 4
    Does this answer your question? [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) It is talking about pointers, but the result is the same with references. – L. F. Dec 08 '19 at 11:09
  • 1
    What you have is undefined behavior. – machine_1 Dec 08 '19 at 11:10

2 Answers2

4

You are returning reference to a local variable. The variable dies when the function returns and your reference dangles. After return reference points to something that as dead and using that reference results in undefined behavior.

fu& fub() {
    fu a;
    fu& re = a;
    return a;
    // a is dead now
}

You can easily detect it with compiler warning e.g. -Wall on g++.

Live on Godbolt.

Oblivion
  • 7,176
  • 2
  • 14
  • 33
4

The reference refers to the deleted object. It is a dangling reference. As a result the program has undefined behavior.

In this particular case the output looks correct only because the memory occupied by the deleted object was not yet overwritten.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335