non-const reference to temporary (was: non-const copy ctor)

Andrew Haley
Sun Apr 9 16:55:00 GMT 2006

Christian Fröbel writes:
 > Hi there,
 > Christian Fröbel wrote:
 > > I'm having problems with a non-const copy constructor.
 > I'd like to correct myself. This problem dosn't seem to be related to the copy 
 > constructor at all. The problem is that I'm not allowed to make a non-const 
 > reference to a temporary object. For example code like this doesn't compile:
 > class C {};
 > void foo (C& c) {}
 > int main (void)
 > {
 > 	foo (C()); // <== problem
 > 	return 0;
 > }
 > The error message I get here is:
 > conversion.cpp:48: error: invalid initialization of non-const reference of 
 > type øC&ù from a temporary of type øCù
 > conversion.cpp:42: error: in passing argument 1 of øvoid foo(C&)ù
 > I read §5.5 in Stroustrup's C++ Programming Language regadring that topic but 
 > couldn't find anything of real use there.

I can.  "The initializer of a const T& need not be an lvalue..."  In
other words, although he doesn't explicitly say so, the initializer of
a const T& has to be an lvalue.

 > I understand that it generally doesn't make sense to alter a
 > temporary object. But why forbid it?

Because, semantically speaking, it makes no sense.

But we're way off topic now.


More information about the Gcc-help mailing list