Use const wherever possible in C++?

后端 未结 5 1339
死守一世寂寞
死守一世寂寞 2020-12-10 13:04

As stated in book Effective C++: \"Use const whenever possible.\", one would assume that this definition: Vec3f operator+(Vec3f &other); would be b

5条回答
  •  失恋的感觉
    2020-12-10 13:06

    C++ FAQ:

    If you find ordinary type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also.

    You should use const when you want to be sure not to change variable accidentally or intentionally. Some constants (globals and class static, strings & integers, but not variables with nontrivial constructor) can be placed in read-only parts of the executable, therefore result in segmentation fault if you try to write to it.

    You should be explicit using const as a specifier on functions that follow this principle as well as on function arguments. If you don't have to change actual argument, make it const. This doesn't limit the possible usages of such function, but extends them, because now they might be used on const arguments, and on const objects.

    In declaration

    const int* foo(const int* const&) const;
    

    every const means something different and yes, obviously it should be used if it is needed.

    Summary

    Using const increases type-safety of your program.

    C++ FAQ:

    [18.3] Should I try to get things const correct "sooner" or "later"?

    At the very, very, very beginning.

提交回复
热议问题