What's wrong with const?

2020-05-16 05:51发布

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

标签: c++ c++11
12条回答
仙女界的扛把子
2楼-- · 2020-05-16 06:21

The problem with const is the programmers that use it incorrectly our inconsistently

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-16 06:24

One thing is that it is still possible subvert it. i.e. it is still legal to do something like this:

void foo(const inst& x)
{
   const_cast<int&> x = 3;
}

You can even use things like memset to subvert it without an explicit const_cast.

This is a trade-off between having the compiler enforce const and allowing some flexibility for non const aware interfaces.

Which leads to another limitation, in that it has not been universally embraced, which is in part due to another problem, which is that using const is an all-or-nothing proposition. If you start using it, you will need to propagate it throughout your code base.

查看更多
我想做一个坏孩纸
4楼-- · 2020-05-16 06:26

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.

查看更多
家丑人穷心不美
5楼-- · 2020-05-16 06:28

The only thing wrong with const is that it is seriously underrated by to many developers. It's one of the best tools in C++'s toolbox, very sharp, and yet not dangerous to cut yourself with.

查看更多
放我归山
6楼-- · 2020-05-16 06:29

The main problem is that you have to write it. It should be the default, and all mutable variables or parameters should be specified explicitly.

查看更多
狗以群分
7楼-- · 2020-05-16 06:29

Most of the answers below state things such as "what is wrong with const is that X people do Y". Those are not answers but symptoms. Those are not things wrong with const. There's barely any wrong thing with const... Those are things wrong with people who can't RTFM.

查看更多
登录 后发表回答