问题描述
在 C++ 中,我有一个只需要对数组进行只读访问但被错误地声明为接收非常量指针的函数:
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* array, size_t count )
{
size_t result = 0;
for( size_t i = 0; i < count; i++ ) {
if( array[i] == 0 ) {
++result;
}
}
return result;
}
我需要为一个 const 数组调用它:
and I need to call it for a const array:
static const int Array[] = { 10, 20, 0, 2};
countZeroes( const_cast<int*>( Array ), sizeof( Array ) / sizeof( Array[0] ) );
这会是未定义的行为吗?如果是这样 - 程序何时会运行到 UB - 执行 const_cast 并调用函数或访问数组时?
will this be undefined behaviour? If so - when will the program run into UB - when doing the const_cast and calling the functon or when accessing the array?
推荐答案
是的,这是允许的(如果有危险!).这是对 const
对象的实际写入会导致未定义的行为,而不是强制转换本身(7.1.5.1/4 [dcl.type.cv]).
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]).
作为 5.2.11/7 [expr.const.cast] 中的标准注释,根据对象的类型,尝试通过指针写入,该指针是丢弃 const
的结果可能会产生未定义的行为.
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.
这篇关于是否允许使用 const_cast 对 const 对象进行只读访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!