// 后置++,返回自增前的值,且返回的是一个右值
const int operator++(int){
int temp(*this);
*this += 1;
return temp;
}
我是在看一本书上看到的,返回类型是const的,随后百度看了下,发现大家博客写的大多也是返回const,我有点想不通,为何?去掉const又何妨呢?
PHP中文网2017-04-17 15:24:22
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.
PHPz2017-04-17 15:24:22
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.
PHP中文网2017-04-17 15:24:22
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++++;