overloaded "operator++" returns a non const, and clang-tidy complains
Asked Answered
I

1

20

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?

Intrigue answered 18/10, 2018 at 9:28 Comment(1)
Note: I logged a bug for this in the past, no reaction yet: bugs.llvm.org/show_bug.cgi?id=41842Hafer
S
29

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.

Semitrailer answered 18/10, 2018 at 9:35 Comment(10)
Oddly, Carnegie-Mellon seem to have changed their mind about this guideline, since it no longer exists here.Romeu
@Romeu - In C++03 that's the only way to prevent this mistake (and there are no move semantics to worry about). I guess they updated it to be with accordance with contemporary C++?Semitrailer
Probably. It's a pity they chose to break all the incoming links rather than leaving a note to that effect.Romeu
I wanted to say option 2 breaks foo(returnsX()++);, but then it feels kinda like a long shot.Stable
@PasserBy - It should break. Assuming X++ behaves as expected, and returns a copy of the old value, it compiles, but is broken already. foo doesn't see the updated value.Semitrailer
I applied option 2 in C++11, but clang-tidy still complains!Phonology
@SergeyKolesnik - Of course it still complains. Option 1 is to do as clang-tidy says to blindly follow DCL21-CPP. Option 2 is not to do it.Semitrailer
@StoryTeller-UnslanderMonica I think it would be helpful if you'd mentioned that in the answer.Phonology
The best option here is to disable this obsolete rule in your clang-tidy config. Trying to follow it will likely trigger other contradictory clang-tidy rules.Sibby
Option 1 will give another clang-tidy error Clang-tidy readability: avoid const value returnBraunstein

© 2022 - 2024 — McMap. All rights reserved.