non-const reference to temporary (was: non-const copy ctor)
Christian Fröbel
cfroebel@web.de
Sun Apr 9 14:44:00 GMT 2006
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 understand that it generally
doesn't make sense to alter a temporary object. But why forbid it? And
sometimes it does make sense (e. g. std::auto_ptr).
Maybe someone of you can shed some light on this topic.
Also, I'd like to know if there's a general way to work around this problem.
Thanks,
Christian
More information about the Gcc-help
mailing list