GCC should warn about "obvious" bugs in binding a reference to temporary. Small test case: struct Foo { Foo(int x): x_(x) { } int& x_; }; int main() { Foo f(0); return f.x_; } Gcc -Wall is silent. Clang detects this clearly: clang++ foo.cc -Wall foo.cc:2:19: warning: binding reference member 'x_' to stack allocated parameter 'x' [-Wdangling-field] Foo(int x): x_(x) { } ^ foo.cc:3:9: note: reference member declared here int& x_; ^ 1 warning generated.
Confirmed.
N.B. that's not a temporary, it's a named lvalue, but we should definitely diagnose it. Since 4.7 GCC does now diagnose similar cases with temporaries resulting from implicit conversions: struct Foo { Foo(short x): x_(x) { } const int& x_; }; int main() { Foo f(0); return f.x_; } t.cc: In constructor ‘Foo::Foo(short int)’: t.cc:2:22: warning: a temporary bound to ‘Foo::x_’ only persists until the constructor exits [-Wextra] Foo(short x): x_(x) { } ^
*** Bug 63606 has been marked as a duplicate of this bug. ***
(In reply to Brooks Moses from comment #0) > GCC should warn about "obvious" bugs in binding a reference to temporary. > > Small test case: > > struct Foo { > Foo(int x): x_(x) { } > int& x_; > }; > > > int main() > { > Foo f(0); > return f.x_; > } > > Gcc -Wall is silent. > > > Clang detects this clearly: > clang++ foo.cc -Wall > foo.cc:2:19: warning: binding reference member 'x_' to stack allocated > parameter 'x' [-Wdangling-field] > Foo(int x): x_(x) { } > ^ > foo.cc:3:9: note: reference member declared here > int& x_; > ^ > 1 warning generated. If we reuse clang's -Wdangling-field name, this would be a new warning, so making it block the relevant meta-bug. (In reply to Jonathan Wakely from comment #2) > N.B. that's not a temporary, it's a named lvalue, but we should definitely > diagnose it. > > Since 4.7 GCC does now diagnose similar cases with temporaries resulting > from implicit conversions: > > struct Foo { > Foo(short x): x_(x) { } > const int& x_; > }; > > int main() > { > Foo f(0); > return f.x_; > } > > t.cc: In constructor ‘Foo::Foo(short int)’: > t.cc:2:22: warning: a temporary bound to ‘Foo::x_’ only persists until the > constructor exits [-Wextra] > Foo(short x): x_(x) { } > ^ This one should be moved to its own separate option per bug 7651
(In reply to Eric Gallager from comment #4) > This one should be moved to its own separate option per bug 7651 Indeed it should, and if we add -Wdangling-field then that would be the ideal option to move it to.