Article View: comp.std.c++
Article #39Re: return type of operator=
From: John M Davison
Date: Wed, 04 Nov 1992 05:19
Date: Wed, 04 Nov 1992 05:19
50 lines
2391 bytes
2391 bytes
In article <1992Nov03.195240.14360@microsoft.com> jimad@microsoft.com (Jim Adcock) writes:
>In article <1992Oct31.025229.6520@cs.brown.edu> sdm@cs.brown.edu (Scott Meyers) writes:
>|Is the return type of operator= an lvalue?
>
>No.
Jim is mistaken; the built-in types return an lvalue in C++ (except for
bit-field assignment, which I don't know about offhand).
>|In particular, if a, b, and c are of built-in type, is this legal?
>|
>| (a = b) = c;
>
>No, it is an error. If (a = b) were an lvalue the same
>as "a" then "a" would be being accessed twice for modification in one
>expression, which in turn is an unconstrained error.
It is not an error. ((a=b)=c) is equivalent to (a=c), except for side
effects, of course.
>My answers are based on the ANSI-C spec
In Standard C, = returns an rvalue. In C++, = returns an lvalue.
Stroustrup talks about this in the "Lvalues" section of "The Evolution
of C++: 1985 to 1989". I quote:
"Note that the default definition of assignment of
an X as a call of
X& operator=(const X&)
makes assignment of Xs produce an lvalue. For uniformity,
this rule has been extended to assignments of built-in
types. By implication, +=, -=, *=, etc. now also produce
lvalues. So -- again by implication -- does prefix ++ and
-- (but not the postfix versions of these operators).
"In addition, the comma and ?: can also produce
lvalues...."
>The "right" thing to do is to return a value, not a reference.
>...Don't return a non-const reference.
Return a non-const reference. C++ does it with its built-in types.
--
John Davison
davisonj@ecn.purdue.edu
Technical Details
Message-ID:
<1992Nov4.051914.25983@en.ecn.purdue.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!europa.asd.contel.com!emory!sol.ctr.columbia.edu!zaphod.mps.ohio-state.edu!sample.eng.ohio-state.edu!purdue!mentor.cc.purdue.edu!noose.ecn.purdue.edu!en.ecn.purdue.edu!davisonjReferences:
<1992Oct31.025229.6520@cs.brown.edu> <1992Nov03.195240.14360@microsoft.com>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c++ Path: arc1-ca.pugleaf.net!sparky!uunet!europa.asd.contel.com!emory!sol.ctr.columbia.edu!zaphod.mps.ohio-state.edu!sample.eng.ohio-state.edu!purdue!mentor.cc.purdue.edu!noose.ecn.purdue.edu!en.ecn.purdue.edu!davisonj From: davisonj@en.ecn.purdue.edu (John M Davison) Subject: Re: return type of operator= Message-ID: <1992Nov4.051914.25983@en.ecn.purdue.edu> Summary: Jim Adcock is wrong wrong wrong Organization: Purdue University Engineering Computer Network References: <1992Oct31.025229.6520@cs.brown.edu> <1992Nov03.195240.14360@microsoft.com> Date: Wed, 4 Nov 92 05:19:14 GMT Lines: 50