【问题标题】:const_cast: override a const statusconst_cast:覆盖一个常量状态
【发布时间】:2012-07-19 18:41:10
【问题描述】:

我正在尝试使用 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 运算符直接覆盖常量变量的常量状态 :-(.

【问题讨论】:

  • 您遇到了什么异常?您发布的代码在 g++ 中很好。
  • 请告诉我们你在哪里调用function1(),并记住使用const_cast从真正的常量对象(在这种情况下为const Object)中删除常量会导致未定义的行为,包括例外情况。
  • 你能把你展示的代码做成一个完整(但仍然很小)的例子吗?很难理解你从这个片段中看到了什么。
  • @cdhowie:仅当有人使用生成的指向非 const 的指针尝试修改对象时。 const int i = 0; int *p = const_cast&lt;int*&gt;(&amp;i); std::cout &lt;&lt; *p; 可以。
  • const_cast 并不神奇,它几乎所有天真的删除 CV 的用途实际上都是未定义的行为。它仅适用于 strchr 之类的东西,您可以将一段代码重用于两个不同的常量。

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


【解决方案1】:

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

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

这是一个代码sn-p:

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 说明符,但改变底层内存的访问模式并不是它的目的、权限或设计。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2019-06-15
    相关资源
    最近更新 更多