sha*_*oth 6 c++ casting const const-cast undefined-behavior
在C++中,我有一个只需要对数组进行只读访问但是被错误地声明为接收非const指针的函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
我需要为const数组调用它:
static const int Array[] = { 10, 20, 0, 2};
countZeroes( const_cast<int*>( Array ), sizeof( Array ) / sizeof( Array[0] ) );
Run Code Online (Sandbox Code Playgroud)
这将是未定义的行为吗?如果是这样 - 程序何时会运行到UB中 - 在执行const_cast并调用functon或访问数组时?
CB *_*ley 14
是的,允许(如果危险!).它是对const对象的实际写入引起的未定义行为,而不是转换本身(7.1.5.1/4 [dcl.type.cv]).
正如5.2.11/7 [expr.const.cast]中的标准注释一样,根据对象的类型,尝试通过丢弃的结果写入指针const可能会产生未定义的行为.