If you remove completely the operator=
method, a default operator=
will be created by the compiler, which implements shallow copy1 and returns a reference to *this
.
Incidentally, when you write
mywidget = mywidget2 = mywidget3;
you're actually calling this default operator=
, since your overloaded operator is designed to work with int
s on the right side.
The chained assignment will stop working, instead, if you return, for example, a value, a const
reference (=>you'll get compilation errors) or a reference to something different from *this
(counterintuitive stuff will start to happen).
Partially related: the copy and swap idiom, i.e. the perfect way to write an assignment operator. Strongly advised read if you need to write an operator=
- The default
operator=
will perform as if there were an assignment between each member of the left hand operand and each member of the right hand one. This means that for primitive types it will be a "brutal" bitwise copy, which in 90% of cases isn't ok for pointers to owned resources.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…