Is using const_cast for read-only access to a const object allowed?

前端 未结 5 1684
南方客
南方客 2020-12-11 18:41

In C++ I have a function that only requires read-only access to an array but is mistakenly declared as receiving a non-const pointer:

size_t countZeroes( int         


        
5条回答
  •  情书的邮戳
    2020-12-11 19:08

    The problem of const_cast is always the same -- it allows you to "break the rules", just like casting to and from void* -- sure you can do that, but the question is why should you?

    In this case it's of course ok, but you should ask yourself why didn't you declare size_t countZeroes( const int* array, size_t count ) in the first place?

    And as a general rule about const_cast:

    1. It may produce hard to find bugs
    2. You're throwing away the const-agreement with the compiler
    3. Basically you're turning the language into a lower-level one.

提交回复
热议问题