是否允许使用const_cast对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; } size\u t countzero(int*数组,size\u t count) { 大小\u t结果=0; 对于(大小i=0;i

是否允许使用const_cast对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; } size\u t countzero(int*数组,size\u t count) { 大小\u t结果=0; 对于(大小i=0;i,c++,casting,constants,undefined-behavior,const-cast,C++,Casting,Constants,Undefined Behavior,Const Cast,我需要为常量数组调用它: static const int Array[] = { 10, 20, 0, 2}; countZeroes( const_cast<int*>( Array ), sizeof( Array ) / sizeof( Array[0] ) ); 静态常量int数组[]={10,20,0,2}; countzero(常量转换(数组)、sizeof(数组)/sizeof(数组[0]); 这是一种未定义的行为吗?如果是,程序何时会运行到UB?在执行常量转换

我需要为常量数组调用它:

static const int Array[] = { 10, 20, 0, 2};

countZeroes( const_cast<int*>( Array ), sizeof( Array ) / sizeof( Array[0] ) );
静态常量int数组[]={10,20,0,2};
countzero(常量转换(数组)、sizeof(数组)/sizeof(数组[0]);

这是一种未定义的行为吗?如果是,程序何时会运行到UB?在执行常量转换并调用函数时,或在访问数组时?

在最初定义为
常量的对象上使用
常量转换
是UB,因此,在调用
const\u cast

时会立即出现未定义的行为,因为您的代码不修改数组,并且您告诉编译器您知道使用
const\u cast
执行什么操作,所以您实际上是可以的。但是,我相信您在技术上调用未定义的行为。最好修复函数声明,或者编写、声明并使用它的const-safe版本。

是的,它是允许的(如果有危险!)。它是对导致未定义行为的
const
对象的实际写入,而不是强制转换本身(7.1.5.1/4[dcl.type.cv])


正如5.2.11/7[expr.const.cast]中的标准所述,根据对象的类型,试图通过指针进行写操作可能会产生未定义的行为。

是的,您可以这样做。不,只要函数真的不尝试写入数组,它就不是未定义的行为。

const\u cast
的问题总是一样的——它允许您“打破规则”,就像在
void*
之间来回转换一样——您当然可以这样做,但问题是为什么要这样做

在这种情况下当然可以,但您应该问问自己,为什么不首先声明
size\t countzero(const int*array,size\t count)

作为有关
常量的一般规则

  • 它可能会产生难以发现的bug
  • 你要放弃与编译器的const协议
  • 基本上你是在把语言变成一种低级语言

  • 不。UB正在向一个const对象写入内容,而不是删除constness。哦,对了,很抱歉,我在互联网上得到了一些相互矛盾的建议。请尝试在“高效C++”或“更高效C++”中阅读如何使用const。它还显示了const_cast的一些有效用法(例如,避免一些代码重复)。-1因为这不是未定义的行为;从历史上看,这会使C++98代码难以与前标准C进行互操作。但是,我完全同意您的建议。我想您不能更改函数声明。。。但是我强烈建议你用一个更好的包装器来编写一个包装器,并在里面做一些肮脏的工作。也许可以尝试一个完全不同的东西:
    size\t numZeros=std::count(Array,Array+sizeof(Array)/sizeof(Array[0]),0)@MP24此函数只是一个问题的简单说明。