When to use const and const reference in function args?

后端 未结 4 1258
无人共我
无人共我 2020-11-28 23:46

When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be c

4条回答
  •  鱼传尺愫
    2020-11-28 23:58

    The general rule is, use const whenever possible, and only omit it if necessary. const may enable the compiler to optimize and helps your peers understand how your code is intended to be used (and the compiler will catch possible misuse).

    As for your example, strings are not immutable in C++. If you hand a non-const reference to a string to a function, the function may modify it. C++ does not have the concept of immutability built into the language, you can only emulate it using encapsulation and const (which will never be bullet-proof though).

    After thinking @Eamons comment and reading some stuff, I agree that optimization is not the main reason for using const. The main reason is to have correct code.

提交回复
热议问题