c++ - 重载的“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 ++
应该返回 const 的参考:
struct X {
X operator++(int); // postfix a++
};
问题:只是clang-tidy 过度保护、错误或者我为什么要将后缀的返回类型声明为const?
解决方案
试图阻止你编写什么都不做的代码是很整洁的:
(x++)++; // Did we just increment a temporary?
这种形式的重载可能很有用,但通常不适用于后缀++
。你有两个选择:
按照 clang-tidy 说的做,但可能会失去移动语义的好处。
左值引用限定重载,以模仿小整数。
X operator++(int) &; // Can't apply to rvalues anymore.
选项 2 更优;防止那些愚蠢的错误,并在适用的情况下保留移动语义。
推荐阅读
- java - 为具有特定请求标头的请求切换 Spring Security
- angular - 无需嵌套即可进行多个异步验证
- java - xml 布局中缺少样式
- vim - How to show vim tab page title more clearly?
- swift - Cannot call value of non-function type '[String : String]'
- typescript - Typescript:定义一个不能容纳任何东西的类型
- amazon-web-services - Cloudfront, Compression, HTTPS Load error
- varnish - Varnish version shows as "retired"
- php - Uncaught exception 'Exception' with message 'View not found [name, type, prefix]: search, feed, searchView'
- angular6 - I can't uninstall the existing service worker