What happens when opeator= returns void rather than T&?

In operator overloading, the assignment operator is normally defined as follows:

T& T::operator =(const T2& b);

which returns T& as result. But I want to know what happens when we return void. For example, the assignment operator of std::atmoic<std::shared_ptr<T>> returns void:

void operator=( std::shared_ptr<T> desired ) noexcept;

as defined here and here. What happens in this case? Is it ok to always implement the assignment operator like this? I guess this prevents assignments like a=b=c; which is good sometimes, isn’t it?

>Solution :

You won’t be able to chain assignments

a = b = c;

(Nor introduce more complicated cases, like (a = b).method(); or if((a = b));.)

OTOH, with void return type you don’t need the ubiquitous return *this; boilerplate.

Leave a Reply