是否使用const_cast只读访问一个const对象? [英] Is using const_cast for read-only access to a const object allowed?

查看:94
本文介绍了是否使用const_cast只读访问一个const对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中我有一个函数,只需要只读访问数组,但错误地声明为接收一个非const指针:

  size_t countZeroes(int * array,size_t count)
{
size_t result = 0;
for(size_t i = 0; i if(array [i] == 0){
++ result;
}
}
返回结果;
}

我需要为一个const数组调用它:

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

countZeroes(const_cast< int *>(Array),sizeof(Array)/ sizeof(Array [0]))

这将是未定义的行为吗?如果是这样,当程序运行到UB时 - 当执行const_cast并调用functon或访问数组时?

解决方案

是的,它是允许的(如果危险!)。它实际上是写入到一个引发未定义行为的 const 对象,而不是转换本身(7.1.5.1/4 [dcl.type.cv])。



作为5.2.11 / 7 [expr.const.cast]中的标准注释,根据对象的类型,尝试通过指针写入,该指针是抛出 const 可能会产生未定义的行为。


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?

解决方案

Yes, it is allowed (if dangerous!). It's the actual write to a const object that incurs undefined behaviour, not the cast itself (7.1.5.1/4 [dcl.type.cv]).

As the standard notes in 5.2.11/7 [expr.const.cast], depending on the type of the object an attempt to write through a pointer that is the result of casting away const may produce undefined behaviour.

这篇关于是否使用const_cast只读访问一个const对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆