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

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

问题描述

最近,我关注了有关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天全站免登陆