Re: Hiding a reference to temporary
Olivier ha scritto:
I was playing around with code (the code did consent) and stumbled
over this :
char const & hideConstRefToTemporary( char const &c )
char const & getChar1( )
char const & getChar2( )
int main( )
std::cout << getChar() << "\n";
std::cout << getChar2() << "\n";
If you try and compile this code with gcc (I used version 4.3.2
20080827 alpha-testing 1), The compiler will complain of a reference
to temporary for the function 'getChar2' but not for the function
Is that a normal behaviour?
The question is ill-formed. Warnings are not a matter treated by the
standard, they are a quality-of-implementation issue. So a compiler can
emit or fail to emit any kind of warning and still that would be
Is the code valid?
It depends on your definition of "valid". The code is well-formed, but
the behaviour is undefined, in both cases.
Is there any word in the C++ standard that talk about this case?
No, because it shouldn't. Even the rule that says that returning a
reference to a temporary is bad is never said explicitly AFAIK, but is
implicit in 3.8.
I know that temporaries can be bound to a const reference as function
arguments, but how does that influence the way you use the variable
representing that temporary ?
Each time a temporary is bound to a reference, the lifetime of the
temporary is extended to be not shorter than the lifetime of the reference.
const int& i = f(); // #1: i is bound to the temporary
/* ... */
// Lifetime of the temporary extended up to the point where i exits
// from scope. Normally it would have been destroyed at the
// end of line #1
However, this rule has no effect on temporaries bound to function
arguments of reference type, because the argument typically has shorter
void g(const int& i);
g(f()); // lifetime of i ends before lifetime of the temporary
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]