在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或访问数组时?