[英]overloaded "operator++" returns a non const, and clang-tidy complains
我刚刚从 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?
试图阻止您编写无所作为的代码是一种叮当声:
(x++)++; // Did we just increment a temporary?
这种形式的重载可能很有用,但通常不适用于 postfix ++
。 您有两个选择:
按照 clang-tidy 说的去做,但可能会失去移动语义的好处。
左值引用限定重载,以模仿小整数。
X operator++(int) &; // Can't apply to rvalues anymore.
选项 2 更优; 防止那些愚蠢的错误,并在适用时保留移动语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.