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'
...