What's wrong with const?

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

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

12条回答
  •  [愿得一人]
    2021-01-31 12:27

    One thing that is "wrong" is that you cannot convert T** to T const * const * which should be allowed because it is not dangerous. Not allowing T** to convert to T const ** is correct, that conversion is not valid.

    I have sometimes mentioned that const actually is a cheap way to "split" your interface into read-only methods and write methods. It would probably be impractical in C++. It would be more practical in Java to have ReadOnly versions of collections though, where they don't have const and where their collection types are more object-orientated.

    const-ness does not propagate: The issue here is that if I pImpl my class, the constness is not "checked" by the compiler, i.e. my interface class can have a "const" method call a non-const method on the pImpl and the compiler won't complain. That is because the only thing my const method is guaranteed not to do is change the pointer to point to a different object, and my pImpl is never going to change. It could even be a const pointer (not pointer to const).

    The lack of proper co-variance between shared_ptr and shared_ptr might be an issue too, although in general I have seen that not to be the problem, but that developers usually typedef their shared_ptrs and rarely typedef the shared_ptr to const. And they will sometimes pass const shared_ptr & and think that they are passing a shared pointer to a const T (as with const T*) which they are not.

提交回复
热议问题