赋值运算符的返回类型 [英] Return type of assignment operator

查看:89
本文介绍了赋值运算符的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定义赋值运算符时,它总是看起来像这样:

When defining an assignment operator, it invariably looks like this:

class X {...};

X& X::operator=(...whatever...);

也就是说,它的返回类型为对X的引用".在这里,参数(...whatever...)可以是X& const X& ,而在使用<一个href ="https://stackoverflow.com/q/3279543/509868">复制和交换惯用法,或任何其他类型.

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.

每个人都建议无论参数如何,都建议返回对X 的非常量引用,这似乎很奇怪.这明确允许使用 (a = b).clear() 之类的表达式,这应该是很好的.

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.

我有不同的意见,我想在代码中禁止使用(x=y).clear(x=y)=z甚至x=y=z之类的表达式.我的想法是这些表达式在一行代码中做的事情太复杂了.所以我决定让我的赋值运算符返回void:

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)

我的X类可以与标准容器(例如std::vector<X>)一起使用吗?

Can my class X be used with standard containers (e.g. std::vector<X>)?

我正在使用C ++ 03(如果有的话).

I am using C++03 (if that matters).

推荐答案

您的课程不符合

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.

这篇关于赋值运算符的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆