C++ const modifier with primitive types

后端 未结 5 2069
死守一世寂寞
死守一世寂寞 2020-12-31 12:16

Should I pay attention on const modifier working with primitive types? Which one is more syntactically correct and why?

First version:

f         


        
5条回答
  •  情书的邮戳
    2020-12-31 13:17

    I would say that the third version is most "correct".

    You tell the compiler that the arguments are const, which is correct since you don't modify them. This can help the compiler with optimizations for passing the arguments, as well as in the calculations.

    And the return type is not const since the caller may want to modify the returned value. If the caller doesn't want to modify the returned value, then it's up to the caller to assign it to a const variable.

    I would also have added const to the function declaration, since the function does not modify anything in the object:

    float Foo::bar(const float a, const float b) const
    

提交回复
热议问题