Article View: comp.std.c++
Article #36Re: return type of operator=
From: Jim Adcock
Date: Tue, 03 Nov 1992 19:52
Date: Tue, 03 Nov 1992 19:52
36 lines
2088 bytes
2088 bytes
In article <1992Oct31.025229.6520@cs.brown.edu> sdm@cs.brown.edu (Scott Meyers) writes: |Is the return type of operator= an lvalue? No. |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. |I couldn't find an answer in the ARM, My answers are based on the ANSI-C spec, under the optimistic assumption that some day the ANSI/ISO-C++ spec will contain equivalently detailed language about what kinds of errors can occur in programs, and what actions compilers can or cannot perform as a result of those errors. |My goal is to determine the correct type for user-defined operator=. If |the return type is to be an lvalue, then for a class C, the return type |should be C&. However, if the return value is not to be an lvalue, then |op= should return a const C&. Two years ago I thought const C& was the |right type, but since then I've become convinced that C& is better. Now |doubt has surfaced in my mind again, and I'd like to put the matter to |rest. The "right" thing to do is to return a value, not a reference. Given the infrequent use of the implied value of an assignment operation, many C++ programmers are lothe to return by value. In which case returning a const reference might be an acceptable hack. You might return void instead in cases where programmers shouldn't reasonably expect to use a side-effect value of assignment. Don't return a non-const reference. This would further confuse users about the illegality of modifying a variable multiple times in one expression.
Technical Details
Message-ID:
<1992Nov03.195240.14360@microsoft.com>Path:
arc1-ca.pugleaf.net!sparky!uunet!microsoft!hexnut!jimadReferences:
<1992Oct31.025229.6520@cs.brown.edu>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c++ Path: arc1-ca.pugleaf.net!sparky!uunet!microsoft!hexnut!jimad From: jimad@microsoft.com (Jim Adcock) Subject: Re: return type of operator= Message-ID: <1992Nov03.195240.14360@microsoft.com> Date: 03 Nov 92 19:52:40 GMT Organization: Microsoft Corporation References: <1992Oct31.025229.6520@cs.brown.edu> Lines: 37