这里不是const修饰符吗? [英] Isn't the const modifier here unnecessary?

查看:144
本文介绍了这里不是const修饰符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective C ++ 项目3说尽可能使用const,并给出一个例子:

  const Rational operator *(const Rational& lhs,
const Rational& rhs);

以防止客户能够提交这样的暴行:

  Rational a,b,c; 
...
(a * b)= c; // invoke operator = on the result of a * b!

但不是函数的非引用返回值allready a

$ p

解决方案

关键在于类类型类型), a = b 只是 a.operator =(b)的缩写,其中operator =成员函数。可以在由 Rational :: operator * 创建的(a * b)的值上调用成员函数。为了执行与内置右值类似的语义( do as ints ),一些作者(Meyers包括)在C ++ 98中推荐使用这种运算符的类返回const-rvalue。 p>

但是,在C ++ 11中,通过const-rvalue返回是一个坏主意,因为它会阻止move语义,因为const rvalues不能绑定到 T& ;



在他的笔记中 概述新的C ++(C + +11) ,Scott Meyers从他的旧书中给出了完全相同的示例,并得出结论,现在认为添加const返回值的设计很差。现在推荐的签名是

  Rational运算符*(const Rational& lhs,const Rational& rhs); 

更新:在评论中,@ JohannesSchaub-litb C ++ 11,您还可以在赋值运算符上使用引用限定符,以便它只接受左值作为其左参数(即 * this 指针,这就是为什么这个特性也被称为rvalue references for * this)。你需要g ++> = 4.8.1(刚发布)或Clang> = 2.9才能使用它。


The "Effective C++" Item 3 says "Use const whenever possible", and it gives an example like:

const Rational operator*(const Rational& lhs, 
                            const Rational& rhs);

to prevent clients from being able to commit atrocities like this:

Rational a, b, c;
...
(a * b) = c;   // invoke operator= on the result of a*b!

But isn't the non-reference return value of functions allready a rvalue? So why bother doing this?

解决方案

The point is that for class types (but not for builtin types), a = b is just a shorthand to a.operator=(b), where operator= is a member function. And member functions can be called on rvalues such (a * b) created by Rational::operator*. To enforce similar semantics as for builtin rvalues ("do as the ints do") some authors (Meyers including) recommended in C++98 to return by const-rvalue for classes with such operators.

However, in C++11 returning by const-rvalue is a bad idea as it will inhibit move semantics because const rvalues cannot bind to T&&.

In his notes An overview of the new C++ (C++11), Scott Meyers gives precisely the same example from his old book, and concludes that it is now considered poor design to add the const return value. The recommended signature is now

Rational operator*(const Rational& lhs, const Rational& rhs);

UPDATE: As implied by @JohannesSchaub-litb in the comments, in C++11 you can also use a reference qualifier on the assignment operator so that it will only accept lvalues as its left argument (i.e. the *this pointer, which is why this feature is also known as "rvalue references for *this"). You'll need g++ >= 4.8.1 (just released) or Clang >= 2.9 to make use of it.

这篇关于这里不是const修饰符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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