Re: Lifetime of a temporary that is bound to a reference
"Markus Schoder" <a3vr6dsg-usenet@yahoo.de> schrieb im Newsbeitrag
news:pan.2007.05.24.18.58.38@yahoo.de...
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.
Why should there be a new temporary? The parameter `value' is clearly a
lvalue and `m_value' will bind directly to it.
I assume that the rvalue Sean Kelly is talking about is the actual parameter
'42' passed to Foo's constructor in my original example, but as I've said, I
don't think that this plays a role here, especially as 8.5.3/5 requires the
rvalue to be a class type for the temporary to be created.
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.
Even if this were a case of the reference member being initialized by a
temporary (I doubt that it works that way) that would not change things
much. The reference member is initialized through a ctor-initializer and
12.2/5 specifies this as a special case where the temporary "persists
until the constructor exits".
I agree. According to my interpretation of the standard, the following code
has undefined behaviour:
#include <iostream>
class Foo
{
const int& m_value;
public:
Foo( const int& value ) : m_value( value ) {}
void f() { std::cout << m_value << std::endl; }
};
int main()
{
Foo( 42 ).f();
}
--
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! ]