C++: constant reference to temporary
问题 There are several questions about lifetime of constant reference on SO, but still I don't get it. Is this piece of code valid? struct S { const int &ref; S( const int &x ) : ref(x) { } }; int main( ) { S s( 0 ); // ... use( s.ref ); // ... return 0; } Intuitively I'd say no, since 0 should expire after the expression ( S s(0); ) is evaluated. However both GCC and CLANG compile it fine, without warnings, and valgrind doesn't detect any runtime error. What am I missing about references? 回答1: