What's wrong with const?

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

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

12条回答
  •  天涯浪人
    2021-01-31 12:47

    const is great. const is important. const-correctness is necessary condition for an API to be good.

    Yet there are two issue I've had with const, repeatedly.

    • There's no way to mark a variable as const retroactively. You must either declare a variable code, in which case you have to initialize it immediatly. What if the initialization code contains an if, though? You have the choice of either omitting the const (undesirably), using operator ? instead of if (harms readability). Java get's that right, BTW - const variables don't have to be initialized right away, they just have to be initialized before they're first read, and they have to be initialized in all branches of an if.

    • There's no way to specifiy that an object passed by reference to a function won't change for the duration of the function call. const T& t does not mean that the object pointed to by t won't change, but only that the reference t cannot be used to change it. The compiller still has to assume that any function call which it does not see into might change the object. It some cases, that prevents quite a few optimizations.

提交回复
热议问题