Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

c++ - overloaded "operator++" returns a non const, and clang-tidy complains

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...