Re: Lifetime of a temporary that is bound to a reference
"Sean Kelly" <sean@f4.ca> schrieb im Newsbeitrag
news:1179948219.618579.282030@x18g2000prd.googlegroups.com...
On May 21, 8:35 pm, Markus Schoder <a3vr6dsg-use...@yahoo.de> wrote:
On Mon, 21 May 2007 13:42:11 -0600, Matthias Hofmann wrote:
But if this code is well defined, then how come the following isn't:
#include <iostream>
class Foo
{
const int& m_value;
public:
Foo( const int& value ) : m_value( value ) {} void f() { std::cout
<< m_value << std::endl; }
};
Foo x( 42 );
int main()
{
// Output is "1" on VC++
// 2005 Express Edition.
x.f();
}
The lifetime of temporaries bound to a constructor's parameters lasts
until the initialisation is completed. So this example has undefined
behaviour.
Are you sure? My reading of 12.2 suggests that a new temporary will
be created when an rvalue is bound to a reference (8.5.3), and this
value should persist for the lifetime of the reference (12.2.5). In
the above example, an intermediate temporary referenced by 'value' may
be destroyed when the ctor exits, but I would expect the temporary
bound to 'm_value' to persist for the life of the object.
8.5.3/5 says that it is implementation-defined whether that new temporary
will be created or not, but I don't think this plays a role here anyway.
The
question is whether in the above example, the reference that determines the
lifetime of the temporary is the formal parameter of the constructor or the
reference member initialized from the former.
If I recall correctly, the lifetime of a temporary is not affected by
re-binding to another reference. For example, the following code should be
undefined behaviour:
const int& r = std::min( 0, 2 );
// 'r' is a dangling reference.
int i = r;
Unfortunately I found no evidence for this in the standard, but I remember
that someone told me that in this newsgroup.
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]