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).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…