lifetime extension of temoraries

N

n.torrey.pines

http://www.artima.com/cppsource/foreach.html says

"temporary objects of derived type can have their lifetime extended by
binding them to a const reference to the base type."

====================================
#include <iostream>

struct base {};

struct derived : public base {
~derived() { std::cout << "derived is dead\n"; }
};

struct ref {
const base& ref_;
ref(const base& x) : ref_(x) {}
};

int main() {
ref r = derived();
std::cout << "ref is alive\n";
}
====================================

If this is the case, how come the output of the above code (in VC++8
and G++ 3.4.4) is

derived is dead
ref is alive


Curiously, if "ref r" is changed to "const base& r", the output
changes for both compilers, AND is now also compiler-dependent (two
temporaries in VC++)

Judging by this thread http://groups.google.com/group/comp.lang.c++/browse_frm/thread/e8c8fb5450c8182d/db7a1fd87bf1b85e
there seems to be little consensus on how the standard should be
interpreted regarding lifetime extensions?
 
F

Fei Liu

http://www.artima.com/cppsource/foreach.html says

"temporary objects of derived type can have their lifetime extended by
binding them to a const reference to the base type."

====================================
#include <iostream>

struct base {};

struct derived : public base {
~derived() { std::cout << "derived is dead\n"; }
};

struct ref {
const base& ref_;
ref(const base& x) : ref_(x) {}
};

int main() {
ref r = derived();
std::cout << "ref is alive\n";
}
====================================

If this is the case, how come the output of the above code (in VC++8
and G++ 3.4.4) is

derived is dead
ref is alive
And what part of the standard says is in question? You are binding the
temporary to a ref object not a const reference to the base type. Once
the base copy operation is done, the derived is dead.
The compiler generates a temporary, which is bound to a const base &,
which is then used to copy construct a ref object.

Fei
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top