returning const references to temporaries/local variables

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

is returning const references to temporaries/local variables always an error (assuming the variable is local, not static, and not a member variable)? Why does g++ only generate warnings, not errors? Because it is legal C++, but not useful? Or undefined behavior?

struct Base1 {};
struct Derived1 : public Base1 {};

const Base1& f1() { Base1 x; return x; }
const Base1& f2() { return Base1(); }
const Base1& f3() { Derived1 x; return x; }
const Base1& f4() { return Derived1(); }

struct Base2 { int foo; };
struct Derived2 : public Base2 {};

const Base2& f5() { Base2 x; return x; }
const Base2& f6() { return Base2(); }
const Base2& f7() { Derived2 x; return x; }
const Base2& b8() { return Derived2(); }

BTW g++ generates a warning for all cases except the last one. I guess there should be a warning as well or am I missing something?

Joachim


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux