Is it better to remove “const” in front of “primitive” types used as function parameters in the header?

后端 未结 5 957
说谎
说谎 2020-12-13 01:40

In the code review process, one of my coworkers mentioned to me that \"const\"s in front of \"primitive types\" used as a function parameter in a header is meaningless, and

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 02:14

    Follow the recommendations given you in code review.

    Using const for value arguments has no semantic value — it is only meaningful (potentially) for implementation of your function — and even in that case I would argue that it is unnecessary.

    edit: Just to be clear: your function’s prototype is the public interface to your function. What const does is offer a guarantee that you will not modify references.

    int a = 7;
    do_something( a );
    
    void do_something(       int& x );  // 'a' may be modified
    void do_something( const int& x );  // I will not modify 'a'
    void do_something(       int  x );  // no one cares what happens to x
    

    Using const is something akin to TMI — it is unimportant anywhere except inside the function whether or not 'x' is modified.

    edit2: I also very much like the information in StoryTeller’s answer

提交回复
热议问题