我应该为赋值运算符使用左值引用限定符吗? [英] Should I use lvalue reference qualifiers for assignment operators?

查看:23
本文介绍了我应该为赋值运算符使用左值引用限定符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我关注了有关 C++ 中表达式赋值的讨论,如下例所示:

Recently, I have followed a discussion about assignments to expressions in C++ as shown in the following example:

string s1, s2, s3;
(s1 + s2) = s3;

使用 C++11 可以将赋值运算符限制为左值引用(在左侧).如下声明赋值运算符时,由于类型不兼容,编译器 Clang 会拒绝代码并显示错误消息.

With C++11 it is possible to restrict the assignment operator to lvalue references (on the left side). When declaring the assignment operators as follow, the compiler Clang rejects the code with an error message due to incompatible types.

auto operator=(const string& rhs) & -> string&;
auto operator=(string&& rhs) & -> string&;

我在任何地方都没有看到过.是否有充分的理由不对赋值运算符使用左值引用限定符(除了在大多数编译器中缺少支持之外)?

I haven't seen this anywhere. Is there a good reason for not using lvalue reference qualifiers for assignment operators (besides missing support in most compilers)?

推荐答案

不为赋值运算符使用左值引用限定符是否有充分的理由(除了在大多数编译器中缺少支持)?

Is there a good reason for not using lvalue reference qualifiers for assignment operators (besides missing support in most compilers)?

不,不是真的.使用左值或右值限定符为左值或右值对象构造正确的接口与使用 const 相同,并且应该以相同的方式接近 - 每个函数都应该考虑限制.分配给右值实际上没有意义,因此应该禁止.

No, not really. Using lvalue or rvalue qualifiers to construct a correct interface for lvalue or rvalue objects is just the same as using const, and it should be approached the same way- each function should be considered for restriction. Assignment to an rvalue doesn't really make sense, so it should be forbidden.

你没有看到它的原因主要是编译器支持不佳 - *this 的右值引用有点像 thread_local,大多数编译器实现者似乎已经把它放在附近从 C++11 实现的特性"堆栈的底部.

The reason you haven't seen it is mostly poor compiler support- rvalue refs for *this is kinda like thread_local, most compiler implementers seem to have put it near the bottom of the "Features to implement from C++11" stack.

这篇关于我应该为赋值运算符使用左值引用限定符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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