Return type of assignment operator

ⅰ亾dé卋堺 提交于 2019-12-01 13:54:17

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/19090023/return-type-of-assignment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!