重载的“operator++"返回一个非常量,和 clang-tidy 抱怨 [英] overloaded "operator++" returns a non const, and clang-tidy complains

查看:72
本文介绍了重载的“operator++"返回一个非常量,和 clang-tidy 抱怨的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚收到了来自 clang-tidy 的以下警告:

I have just got the following warning from 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 开始的).

Unfortunately the link which they are providing there does not work and https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046682 has no easy way to find exactly this rule (seemingly the DCL rules start from 50).

但是无论我在标准中的哪个位置(例如 16.5.7 Increment and decrement [over.inc]),我都没有发现 postfix operator ++ 应该返回一个 const 的参考:

But regardless where I look in the standard (for ex 16.5.7 Increment and decrement [over.inc]), I find no reference that postfix operator ++ should return a const:

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

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

Question: is just clang-tidy overly protective, erroneous or why would I want to declare the return type of the postfix to be const?

推荐答案

试图阻止你编写无所作为的代码是一种铿锵的方法:

It's clang-tidy trying to stop you from writing code that accomplishes nothing:

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

这种重载形式可能有用,但通常不适用于后缀++.您有两个选择:

Such forms of overloading may be useful, but not usually for postfix ++. You have two options:

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

  1. Do as clang-tidy says, but then maybe lose the benfeits of move semantics.

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

lvalue ref-qualify the overload instead, to mimic the little ints.

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

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

Option 2 is superior; prevents those silly mistakes, and retains move semantics if applicable.

这篇关于重载的“operator++"返回一个非常量,和 clang-tidy 抱怨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆