Article View: gnu.g++.lib.bug
Article #564Should "operator =" be made to return *this, by convention?
From: Doug Lea
Date: Sat, 03 Feb 1990 12:03
Date: Sat, 03 Feb 1990 12:03
31 lines
2020 bytes
2020 bytes
>
> C programmers are accustomed to expecting = to return the value
> assigned. However, in a few classes--for example, String, Integer
> and Rational-- operator == returns void. Is there a good reason
> for this? Could they be made to return String&, Integer& and
> Rational& *this without causing problems?
>
The reason that X= (+=, -=, etc.) and = operators return void is to
facilitate simple subclassing. While `utility' classes like String,
Integer, etc., are not designed for extensive subclassing (since no
members are virtual (which, in turn is motivated by efficiency
considerations)), it is often convenient to create simple subclasses
like class Line : public String. If you do this, then it is most
desirable that inherited operators return void. Otherwise, unexpected
type matches often occur. For example, if operator << (ostream&,
Line&) were redefined for Line, but op += were inherited from String,
and had return value String&, then
{ Line l; ...; cout << (l += "\n"); }
would invoke op << (ostream&, String&), which is probably not
what anyone would have in mind. This is avoided by having String::+=
return void, making this usage illegal.
Problems like this outweigh the syntactic convenience of supporting
multiple right-associative uses of X= and =. A good rule of thumb
about all this is that no non-virtual member functions should
ever return *this by reference. (This rule is broken in a few places
in libg++ for various reasons though.)
-Doug
Technical Details
Message-ID:
<9002031203.AA26081@g.oswego.edu>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!G.OSWEGO.EDU!dlReferences:
<9002030548.AA00886@life.ai.mit.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!G.OSWEGO.EDU!dl From: dl@G.OSWEGO.EDU (Doug Lea) Newsgroups: gnu.g++.lib.bug Subject: Should "operator =" be made to return *this, by convention? Message-ID: <9002031203.AA26081@g.oswego.edu> Date: 3 Feb 90 12:03:03 GMT References: <9002030548.AA00886@life.ai.mit.edu> Sender: root@tut.cis.ohio-state.edu Reply-To: dl@oswego.oswego.edu Distribution: gnu Organization: GNUs Not Usenet Lines: 31