重载 "operator++" returns 一个非常量,clang-tidy 抱怨
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
不幸的是,他们在那里提供的 link 不起作用,并且 https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046682 没有简单的方法来准确找到这个规则(似乎 DCL 规则从 50 开始)。
但是无论我在哪里查看标准(对于 ex 16.5.7 增量和减量 [over.inc]),我都没有找到后缀 operator ++
应该 return 常量的参考:
struct X {
X operator++(int); // postfix a++
};
问题:clang-tidy 是否过度保护、错误或者为什么我要将后缀的 return 类型声明为 const?
试图阻止您编写无所作为的代码是很整洁的:
(x++)++; // Did we just increment a temporary?
这种形式的重载可能有用,但通常不用于后缀++
。您有两个选择:
照 clang-tidy 说的做,但可能会失去移动语义的好处。
lvalue ref-qualify 重载,以模仿小整数。
X operator++(int) &; // Can't apply to rvalues anymore.
选项2更好;防止那些愚蠢的错误,并在适用时保留移动语义。
我刚从 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
不幸的是,他们在那里提供的 link 不起作用,并且 https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046682 没有简单的方法来准确找到这个规则(似乎 DCL 规则从 50 开始)。
但是无论我在哪里查看标准(对于 ex 16.5.7 增量和减量 [over.inc]),我都没有找到后缀 operator ++
应该 return 常量的参考:
struct X {
X operator++(int); // postfix a++
};
问题:clang-tidy 是否过度保护、错误或者为什么我要将后缀的 return 类型声明为 const?
试图阻止您编写无所作为的代码是很整洁的:
(x++)++; // Did we just increment a temporary?
这种形式的重载可能有用,但通常不用于后缀++
。您有两个选择:
照 clang-tidy 说的做,但可能会失去移动语义的好处。
lvalue ref-qualify 重载,以模仿小整数。
X operator++(int) &; // Can't apply to rvalues anymore.
选项2更好;防止那些愚蠢的错误,并在适用时保留移动语义。