1

I am compiling with g++ 4.8.4 under Ubuntu.

I cannot understand why the code below is working correctly means that prints always on console some output without crashing.

My believe is that the function foo() is assigned a temporary object that will last until the function foo() finishes its execution.

Surely the output argument will point to the same address on the stack where that temporary has been allocated, but I was surprised to find that each call to A::hello() works fine.

I thought that any access to that area of memory should be avoided.

I wanted to double check with 'valgrind' and it is also saying that all is ok. I tried to recompile with -Wstack-protector and nothing.

Do you know why it is happening? Is my believe wrong or it is simply one of those 'undefined' C++ behaviour that is best to avoid?

 #include <iostream>     
 using namespace std;

 struct A {
    A(): a(10) { cout << "a" << endl;  }
   ~A() {cout << "bye" << endl; }
    void hello() const { cout << "hi " << a << endl; }
 };

 const A& foo(const A& a = A()) {
   return a;
 }

 int main() {
   for( int i = 0; i < 10 ; i++) {
      const A& a = foo();
      a.hello();
   }
   return 0;
 }


 Output
 'a' 
 'bye'
 'hi 10'
 'a' 
 'bye'
 'hi 10'
  ...
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173
  • 1
    Undefined Behaviour can do *anything*, including appearing to work. In this case, the value just doesn't happen to get overwritten before you print it. – BoBTFish Dec 22 '15 at 15:34

1 Answers1

4

The behaviour is undefined.

Binding a const reference to an anonymous temporary extends the lifetime of that anonymous temporary to the lifetime of that const reference.

But the attempted re-binding of the returned reference to a in foo will not extend the lifetime: lifetime extension is not transitive. So a is a dangling reference in main().

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • do you know whether this behaviour got a name so that I can get collect more info? Still I am a bit puzzled.. – Abruzzo Forte e Gentile Dec 22 '15 at 15:52
  • I found enlightment in two important points I missed http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const and there is another one here http://stackoverflow.com/questions/15267676/reference-to-an-unnamed-temporary-object-life-time – Abruzzo Forte e Gentile Dec 22 '15 at 16:07