c++ - 重载 "operator++"返回一个非常量,clang-tidy 提示

标签 c++ operator-overloading postfix-operator clang-tidy

我刚从 clang-tidy 收到以下警告:

overloaded "operator++" returns a non-constant object 
 instead of a constant object type

https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html

不幸的是,他们提供的链接不起作用,https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046682没有简单的方法可以准确地找到这个规则(貌似DCL规则是从50开始的)。

但是无论我在标准的哪个位置查看(例如 16.5.7 增量和减量 [over.inc]),我都没有发现后缀 operator++ 应该返回一个常量:

struct X {
    X operator++(int); // postfix a++
};

问题:clang-tidy 是否过度保护、错误或者为什么我要将后缀的返回类型声明为 const?

最佳答案

试图阻止您编写无所作为的代码是 clang-tidy:

(x++)++; // Did we just increment a temporary?

这种形式的重载可能有用,但通常对后缀 ++ 没有用。您有两个选择:

  1. 按照 clang-tidy 所说的去做,但可能会失去移动语义的好处。

  2. lvalue ref-qualify 重载,以模仿小整数。

    X operator++(int) &; // Can't apply to rvalues anymore.
    

选项 2 更优;防止那些愚蠢的错误,并在适用时保留移动语义。

关于c++ - 重载 "operator++"返回一个非常量,clang-tidy 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871026/

相关文章:

c++ - 前缀和后缀运算符继承

c++ - 重定向 C++ 流

c++ - 从 constexpr 构造 const 数组

c - 难以理解指针操作

c# - 具有在 C# 中可见的算术运算符的 F# 结构

c++ - 重载虚运算符 -> ()

c++ - 使用堆栈和迭代器编写后缀计算器

c# - 从另一个进程获取win32线程的StartAddress

c++ - 尝试将 Web 浏览器嵌入到 C++ Win32 项目中。关于 MyIOleInPlaceFrameTable 的错误

c++ - 为什么在重载 = 运算符时通过引用返回?