Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clang-tidy: getting postfix operator++ right [duplicate]

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?

like image 495
Ferenc Deak Avatar asked Nov 14 '22 21:11

Ferenc Deak


1 Answers

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. Do as clang-tidy says, but then maybe lose the benfeits of move semantics.

  2. 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.

like image 192
StoryTeller - Unslander Monica Avatar answered Dec 17 '22 01:12

StoryTeller - Unslander Monica