I have this code:
#include <iostream>
using std::cout;
using std::endl;
struct Int {
const int& val;
};
Int test(){
return Int {30};
}
int main()
{
Int i = Int{30};
cout << i.val << endl;
Int j = test();
cout << j.val << endl;
return 0;
}
Compile with -std=c++11 -O2
will output:
30
0
And a warning:
main.cpp: In function 'int main()':
main.cpp:18:15: warning: '<anonymous>' is used uninitialized in this function [-Wuninitialized]
cout << j.val << endl;
Is i.val
a dangling reference? As far as I understand, the Int{30}
temporary will be destroyed at the semi-colon, and i.val
will be bound to the temporary's val
which has been destroyed already. Is it correct?
And why the compiler says j
is uninitialized, and j.val
is 0?