c++ - 后置++重载返回类型为何是const类型的?
迷茫
迷茫 2017-04-17 15:22:22
0
3
619
// 后置++,返回自增前的值,且返回的是一个右值
const int operator++(int){
    int temp(*this);
    *this += 1;
    return temp;
}

我是在看一本书上看到的,返回类型是const的,随后百度看了下,发现大家博客写的大多也是返回const,我有点想不通,为何?去掉const又何妨呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
Ty80

The class author writes this to emphasize that the returned result is only used as a value, and the result is not allowed to be modified as an object. Removing const will no longer have this restriction. For example, you can write cout << (a++).modify() without being blocked by the compiler.

PHPzhong

Following C++11:

The built-in postincrement expression is prvalue. The standard stipulates that non-class non-array prvalues ​​will not be const/volatile modified. int operator++(int); is prvalue when called. Adding const to this return value type is redundant (the book may be writing randomly). Generally speaking, operator overloading should maintain similar semantics to the built-in version of the operator, so just add it to prvalue.

To prevent prvalue from calling non-const member functions, please use ref-qualifier, for example auto modify() &;

The const-modified prvalue will not match non-const rvalue references, such as preventing move semantics, which in most cases will only bring additional runtime overhead. Returning const values ​​is obsolete.

洪涛

I haven’t written C++ for a long time and I kind of forgot about it, but I can give you an example 1++; int a = 2; a++++;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template