This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]