By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,191 Members | 749 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,191 IT Pros & Developers. It's quick & easy.

lifetime extension of temoraries

P: n/a
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....7a1fd87bf1b85e
there seems to be little consensus on how the standard should be
interpreted regarding lifetime extensions?

Mar 22 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
n.************@gmail.com wrote:
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
>
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....7a1fd87bf1b85e
there seems to be little consensus on how the standard should be
interpreted regarding lifetime extensions?
Mar 22 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.