One might be tempted to make the copy-assignment operator return void
if you won't ever need chained assignments (as shown in the other answers) anyway. After all, chained assignments are often hard to read and understand, so not allowing them might be considered an improvement.
However, an often overlooked aspect is that void operator=(Poly& const)
means that your type would no longer fulfuill the CopyAssignable
concept, which requires a T&
return type.
A type which does not fulfill the CopyAssignable
concept cannot be officially used for some standard-container operations, for example std::vector::insert
, which means that the following seemingly innocent piece of code yields undefined behaviour, even though it probably runs perfectly fine:
#include <vector>
struct Poly
{
void operator=(Poly const&) {} // Poly is not CopyAssignable
};
int main()
{
std::vector<Poly> v;
Poly p;
v.insert(v.begin(), p); // undefined behaviour
}
As the C++ standard explains in § 17.6.4.8/2.3 where it talks about constraints on programs using the standard library:
(...) the effects are undefined in the following cases:
(...) for types used as template arguments when instantiating a
template component, if the operations on the type do not implement the
semantics of the applicable Requirements subclause (...).
Of course, it's precisely because of the undefined behaviour that a compiler is allowed to ignore the error and make the program behave nicely, matching the obviously intended behaviour. But it's not required to do so.
You should also consider that you cannot predict all future uses of your Poly
type. Someone might write some template function such as:
template <class T>
void f(T const& t)
{
T t2;
T t3 = t2 = t;
// ...
}
This function would then not work with your Poly
class.
Just don't violate this C++ convention and you won't run into troubles.
I am just new to C++
part has been lost in an (otherwise well meant) edit, and since variations ofp2 = &p1
resurfaced in the comments... The&
in thePoly& Poly::operator=
declaration means that the operator returns a reference - to itself in this case, which is precisely whatreturn *this;
does. On the other hand, the&
in&p1
evaluates to the address ofp1
, which is aPoly*
pointer, and cannot be assigned to aPoly
object. Do not confuse the two meanings of&
in the two different contexts. – Spirochete