What's wrong with const?

前端 未结 12 2065
無奈伤痛
無奈伤痛 2021-01-31 12:06

What are the known shortfalls of const in C++ and C++0x?

12条回答
  •  不知归路
    2021-01-31 12:37

    "issues"?

    If you aren't going to be modifying the value of a passed pointer (it is used purely for pass-by-reference input to a function), mark it is const. Ditto if the value of a particular variable will not change after its initialization. If a function is safe to call on a const class instance, mark it const too. The more items are correctly annotated const, the less likely you are to inadvertently make a mistake and the more optimizations the compiler will be theoretically able to perform in the absence of complete knowledge (such as when compiling with only function prototypes available).

    Modern versions of gcc have support for warning when you try to cast a const variable to a non-const one. I suggest you leave those warnings enabled.

    The only thing to watch out for is exactly what you are marking const; const char * foo() is not the same as char * foo() const.

提交回复
热议问题