是否允许以下内容:
const int const_array[] = { 42 };
int maybe_inc(bool write, int* array) {
if (write) array[0]++;
return array[0];
}
int main() {
return maybe_inc(false, const_cast<int *>(const_array));
}
Run Code Online (Sandbox Code Playgroud)
特别地,它是确定以铸远的常量性const_array,将其定义为const,只要对象是不实际修改,如在实施例?
在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或访问数组时?