Re: reference to non-const temporary
Ethan Eade wrote:
I'm curious -- why aren't temporaries allowed to be passed as non-const
references? It seems slightly arbitrary, since non-const methods can be
called on them anyway.
It is arbitrary. IIRC, the rule was added to the language because
programmers were getting unexpected results from code like:
void add_one( long& x ) { x = x + 1; }
int i = 1;
add_one( i );
assert( i == 2 );
At first glance, it's easy to imagine that add_one( i ) will operate on
i, but, of course, it doesn't -- it operates on a temporary, the result
of the implicit conversion from int to long.
It's possible to say, "Well, don't make that mistake." But I gather
that, in real life, programmers *did* make this mistake, often enough
that the "const rule" was added in order to catch it.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]