And*_*rew 0 c++ coding-style increment operator-keyword
在C++中,无论我在web中看到后缀增量运算符声明的示例,它总是被声明为
T& operator++(int);
Run Code Online (Sandbox Code Playgroud)
而且我相信这是后缀增量的正确语法,不是吗?
问题在于,每当我声明后缀增量时,我都会使用const关键字声明返回类型,以便它变为类似lvalue.
请参阅示例代码:
class AClass
{
int foo;
public:
AClass(void) : foo(0) {};
// Suffix increment operator
// Consider adding const to return type
/* const */ AClass operator++(int)
{
AClass cp(*this);
foo++;
return cp;
};
// Prefix increment operator
AClass& operator++()
{
foo++;
return *this;
};
};
int main(int argc, const char* args[])
{
/* This code would fail to compile.
int bar = 5;
(bar++)++;
*/
// Similarily, I would expect this to fail
// but it will succeed unless I use const return type.
AClass a;
(a++)++;
}
Run Code Online (Sandbox Code Playgroud)
我从来没有遇到过这样一个const声明的运算符的问题,我知道它已经从一个笨拙的同事的bug中保存了我们的代码.所以,我的问题是:
非常感谢你的回答!
后缀增量返回临时值,而不是引用(这意味着您的第一个签名是错误的):
T& operator++() // prefix
{
this->increment();
return *this;
}
T operator++(int) // suffix
{
// Almost always, you'll have this code:
T tmp(*this); ++(*this); return tmp;
}
Run Code Online (Sandbox Code Playgroud)
有些人喜欢对后缀运算符的返回值进行const限定,以避免编写愚蠢的东西
(a++).modify_me();
Run Code Online (Sandbox Code Playgroud)
不修改a(它适用modify_me于临时对象).对比
(++a).modify_me();
Run Code Online (Sandbox Code Playgroud)
然后递增a然后修改它.
就个人而言,我认为没有必要(因为你可能对副作用感兴趣modify_me).而且,在C++ 11中,您可能希望将所述临时绑定到(非常量)右值引用.Const限定后缀运算符的返回类型会禁用此可能性.
| 归档时间: |
|
| 查看次数: |
826 次 |
| 最近记录: |