------- Comment #2 from james dot kanze at gmail dot com 2007-11-12 17:56 ------- (In reply to comment #0) > class A{ > // .... > };
> class B{ > public: > explicit B(const A& a) > : i_a(a) > { > } > ~B() > { > } > private: > const A& i_a; > }; > A returnA( const char* arg ) > { > return A(/*arg*/); > } > foo() > { > const A& aRef = returnA("FirstObject"); // ..... (1) > { > const B b(returnA("SecondObject")); // ..... (2) Undefined behavior here. The temporary returned by returnA must be destructed at the end of the full expression. > ///... > typedef int outofscope_block; // ..... (3) > } > typedef char outofscope_function; // ..... (4) > } > temporary object created and referenced by aRef is being > deleted when aRef goes out of scope in foo, as Expected. > temporary object created and referenced by B::i_a is being > deleted right after object b's construction, Not expected. It > should(?) have the same life time as the B::i_a(thus b), such > as deleted _after_ line (3) --- If this assumpsion is false, > then what's the difference between a 'plain reference' and > 'member reference' herein?? The difference is that the temporary is not used to initialize the member reference. The temporary is used to initialize the reference argument of B's constructor. It's lifetime is that of the reference argument of B's constructor (or the end of the full expression, which ever is longer). There is a special rule concerning temporaries used to initialize member references, however. If you'd have written: B::B() : i_a( returnA() ) { } the temporary would only have the lifetime of the constructor, despite having been bound to a reference with a longer lifetime. I presume that this is mainly because it would be almost impossible to implement otherwise. > BTW, it works as expected on SunCC compiler. It core dumps on > gcc 3.3.3 while having (empty/invalid) data for i_a on gcc > 4.1.2 but not coring. It doesn't work with Sun CC *if* the compiler is invoked with the necessary options for standard conformance. In this case, you need -features=tmplife. For historical reasons, Sun destructs temporaries later (much later, in fact) than required by the standard. -- James Kanze (GABI Software) email:[EMAIL PROTECTED] Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'Ãcole, France, +33 (0)1 30 23 00 34 -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=33885