const_cast:覆盖const状态

时间:2012-07-20 13:17:39

标签: c++ const undefined-behavior const-cast

我正在尝试使用const_cast运算符并尝试覆盖作为参数传递的参数o的const状态:

void function1 (const Object *o)
{
    ...
    function2( const_cast < Object *> ( o ) ); //Exception in g++
}

void function2 (Object *o) {}

但是覆盖o的const状态会在g ++(GNU / Linux)中引发异常,在VS 2010(Win)中它运行良好......

有没有更可靠的方法来覆盖函数参数的const状态?

更新

MSDN写道:你不能使用const_cast运算符直接覆盖常量变量的常量状态: - (。

1 个答案:

答案 0 :(得分:3)

  

MSDN写道:你不能使用const_cast运算符直接覆盖常量变量的常量状态: - (。

const_cast允许您从指针中删除const说明符,但它不会影响值本身的“const状态”。编译器可能会决定将值放入只读内存(好吧,它是const!),然后尝试修改它,即使通过const_cast,也可能导致访问冲突。

以下是代码段:

static const int A = 1; // it's constant, it might appear on a read-only memory page
static int B = 2; // it's a regular variable

const int* pA = &A; // a const pointer
int* pB1 = &B; // a pointer
const int* pB2 = &B; // a const pointer to regular variable

*pA = 0; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pA) = 1; // Runtime error, although const specifier is stripped from the variable, it is still on read-only memory and is not available for updates
*pB1 = 2; // OK
*pB2 = 3; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pB2) = 4; // OK, we stripped const specifier and unlocked update, and the value is availalbe for update too because it is a regular variable

也就是说,const_cast在编译期间删除了const说明符,但是改变底层内存的访问模式并不是它的目的,权限或设计。