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

前端 未结 5 1683
南方客
南方客 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: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.

提交回复
热议问题