mirror of
https://github.com/isocpp/CppCoreGuidelines.git
synced 2025-12-17 12:44:42 +03:00
Add F.47 - Assignment operators return T&
As discussed in https://github.com/isocpp/CppCoreGuidelines/issues/422
This commit is contained in:
@@ -2873,6 +2873,38 @@ Declaring `main` (the one global `main` of a program) `void` limits portability.
|
|||||||
* The compiler should do it
|
* The compiler should do it
|
||||||
* If the compiler doesn't do it, let tools flag it
|
* If the compiler doesn't do it, let tools flag it
|
||||||
|
|
||||||
|
### <a name="Rf-assignment-op"></a>F.46: Return `T&` from assignment operators.
|
||||||
|
|
||||||
|
##### Reason
|
||||||
|
|
||||||
|
The convention for operator overloads (especially on value types) is for
|
||||||
|
`operator=(const T&)` to perform the assignment and then return (non-const)
|
||||||
|
`*this`. This ensures consistency with standard library types and follows the
|
||||||
|
principle of "do as the ints do."
|
||||||
|
|
||||||
|
##### Note
|
||||||
|
|
||||||
|
Historically there was some guidance to make the assignment operator return
|
||||||
|
`const T&`. This was primarily to avoid code of the form `(a=b)=c` - such code
|
||||||
|
is not common enough to warrant violating consistency with standard types.
|
||||||
|
|
||||||
|
##### Example
|
||||||
|
|
||||||
|
class Foo
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
...
|
||||||
|
Foo& operator=(const Foo& rhs) {
|
||||||
|
// Copy members.
|
||||||
|
...
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
##### Enforcement
|
||||||
|
|
||||||
|
This should be enforced by tooling by checking the return type (and return
|
||||||
|
value) of any assignment operator.
|
||||||
|
|
||||||
### <a name="Rf-capture-vs-overload"></a> F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)
|
### <a name="Rf-capture-vs-overload"></a> F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user