我刚刚从 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 Increment and decrement [over.inc]),我都找不到后缀
operator ++
的引用。应该返回一个常量:struct X {
X operator++(int); // postfix a++
};
问题:只是 clang-tidy 过度保护、错误或为什么我要将后缀的返回类型声明为 const?
最佳答案
试图阻止您编写无所作为的代码是一种 clang :
(x++)++; // Did we just increment a temporary?
这种形式的重载可能很有用,但通常不适用于 postfix ++
.您有两个选择:X operator++(int) &; // Can't apply to rvalues anymore.
选项 2 更优;防止那些愚蠢的错误,并在适用时保留移动语义。
关于c++ - 重载 "operator++"返回非常量,并且 clang-tidy 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67785525/