When defining an assignment operator, it invariably looks like this:
class X {...};
X& X::operator=(...whatever...);
That is, it has the return type "reference to X". Here, parameters (...whatever...
) can be X&
, const X&
, just X
when using the copy-and-swap idiom, or any other type.
It seems strange that everyone recommends returning a non-const reference to X
, regardless of the parameters. This explicitly allows expressions like (a = b).clear()
, which is supposed to be good.
I have a different opinion, and I want to disallow expressions like (x=y).clear
, (x=y)=z
, and even x=y=z
in my code. My idea is that these expressions do too complex things on a single line of code. So I decided to have my assignment operators return void
:
void X::operator=(X) {...}
void X::operator=(int) {...}
Which negative effects does this have? (except looking different than usual)
Can my class X be used with standard containers (e.g. std::vector<X>
)?
I am using C++03 (if that matters).
Your class does not meet the CopyAssignable concept (§17.6.3.1) so it is no longer guaranteed by the standard to work with the standard containers that require this (e.g. std::vector
requires this for insert
operations).
Besides that, this behavior is not idiomatic and will be perceived as surprising by programmers using your code. If you want to disallow chaining, consider adding a named function that does the assignment instead.
Just don't try to change the behavior of idiomatic operators in subtle ways like this. It will make your code harder to read and maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With