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

前端 未结 5 1675
南方客
南方客 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 18:48

    Yes, you can do that. No, it is not undefined behavior as long as the function truely does not try to write to the array.

    0 讨论(0)
  • 2020-12-11 18:55

    Using const_cast on an object which is initially defined as const is UB, therefore the undefined behaviour comes about immediately at the point you call const_cast.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-11 19:10

    Yes, it is allowed (if dangerous!). It's the actual write to a const object that incurs undefined behaviour, not the cast itself (7.1.5.1/4 [dcl.type.cv]).

    As the standard notes in 5.2.11/7 [expr.const.cast], depending on the type of the object an attempt to write through a pointer that is the result of casting away const may produce undefined behaviour.

    0 讨论(0)
  • 2020-12-11 19:10

    Since your code does not modify the array, and you told the compiler you know what you are doing by using the const_cast, you will actually be OK. However, I believe you are technically invoking undefined behaviour. Best to get the function declaration fixed, or write, declare and use the const-safe version of it.

    0 讨论(0)
提交回复
热议问题