gpt4 book ai didi

C++ 后缀自增运算符的常量返回类型

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:08 25 4
gpt4 key购买 nike

在C++中,无论我在网络上看到后缀递增运算符声明的例子,它总是被声明为

T& operator++(int);

我相信这是后缀增量的正确语法,不是吗?

问题是,每当我声明后缀增量时,我都会用 const 关键字声明返回类型,这样它就变成了类似左值的。

请看示例代码:

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++)++;
}

我从来没有遇到过这样一个声明为 const 的运算符的问题,而且我知道它已经从一个笨拙的同事制造的错误中拯救了我们的代码。所以,我的问题是:

  1. 这种做法有什么缺点吗?这确实是一种好做法吗?
  2. 什么是真正正确的后缀运算符声明(我指的是标准)?
  3. 如果这不是标准规定的方式,但已经是一个很好的做法,它不应该成为一个标准吗?

非常感谢您的回答!

最佳答案

后缀增量返回一个临时的,而不是一个引用(这意味着你的第一个签名是错误的):

T& operator++() // prefix
{
this->increment();
return *this;
}

T operator++(int) // suffix
{
// Almost always, you'll have this code:
T tmp(*this); ++(*this); return tmp;
}

有些人喜欢对后缀运算符的返回值进行 const 限定,以避免写出像这样的愚蠢的东西

(a++).modify_me();

它不修改 a(它将 modify_me 应用于临时对象)。对比

(++a).modify_me();

递增 a 然后修改它。

我个人认为没有必要(因为您可能对 modify_me 的副作用感兴趣)。此外,在 C++11 中,您可能希望将所述临时绑定(bind)到(非 const)右值引用。限定后缀运算符的返回类型的 Const 禁用了这种可能性。

关于C++ 后缀自增运算符的常量返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7905172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com