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;
}
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] ) );
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…