Re: reference to non-const temporary
Ethan Eade wrote:
johnchx2@yahoo.com wrote:
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 );
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.
That makes sense. But surely the restriction can be limited to
temporaries created by implicit conversion.
As Seungbeom Kim points out above, the rule in its current form merely
encourages ugly use of methods that return a reference to the object:
struct Foo {
Foo& self() { return *this; }
};
Foo make();
void use(Foo& foo);
int main() {
use(make().self());
}
That seems silly and pointless.
The example program is somewhat contrived. What does the use() function
do exactly? There should be just one answer to that question. So either
use() should perform some operation for which foo serves as input (in
which case foo should be declared a const reference) or use() should
perform some operation upon its foo parameter (in which case passing a
temporary wouldn't make much sense).
In short there is no defect in the language illustrated by the sample
code, but merely a muddled interface.
Greg
---
[ 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 ]