What's wrong with const?

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

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

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 12:29

    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 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.

提交回复
热议问题