Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of assignment operator

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).

like image 571
anatolyg Avatar asked Sep 30 '13 08:09

anatolyg


Video Answer


1 Answers

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.

like image 93
ComicSansMS Avatar answered Oct 01 '22 19:10

ComicSansMS