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
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).
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++
};
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:
Do as clang-tidy says, but then maybe lose the benfeits of move semantics.
lvalue ref-qualify the overload instead, to mimic the little ints.
X operator++(int) &; // Can't apply to rvalues anymore.
Option 2 is superior; prevents those silly mistakes, and retains move semantics if applicable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With