From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 109fba,3bb0dcf4dc92e48d X-Google-Attributes: gid109fba,public X-Google-Thread: fee84,3bb0dcf4dc92e48d X-Google-Attributes: gidfee84,public From: ark@research.att.com (Andrew Koenig) Subject: Re: Mysterious DEC OSF C++ compiler warning Date: 1995/12/19 Message-ID: #1/1 X-Deja-AN: 122288072 references: <4b4rog$m80@holly.cc.uleth.ca> organization: AT&T Bell Laboratories, Murray Hill NJ newsgroups: comp.lang.c++,comp.unix.osf.osf1 In article <4b4rog$m80@holly.cc.uleth.ca> Marc Roussel writes: > // foo.h: > class junk > { double a; > public: > junk(void) {}; > junk(double x) { a = x;}; > junk & operator = (junk & x) { a = x.a; return(*this);}; > }; // ... > junk x; > x = junk(2); > The warning is > foo.c:10: warning: In this statement, the initialization of a non-const > reference requires a temporary for "junk(2)". When you defined the copy constructor for junk, you said it requires an lvalue as its argument because you said junk & operator = (junk & x) { /* ... */ } instead of junk & operator = (const junk & x) { /* ... */ } A parameter that is a reference to const will accept an rvalue, but not a parameter that is a plain reference. After all, if you did not intend to modify the parameter, why did you not make it const? So when you call x = junk(2); you have said you intend to modify 2, which you can't do. By rights, the compiler should reject your program with an error message. However, many compilers generate a temporary and warn about it because that's what cfront used to do. The reason for cfront's behavior, in turn, is that it dates back to when that was actually the intended compiler behavior. -- --Andrew Koenig ark@research.att.com