从(指向const的指针)到(指向非const的指针)的转换是无效的c ++吗?

Gav*_*nes 8 c++ pointers casting const g++

我确信以下代码不应该编译.但是,在g ++中,它确实可以编译!请参阅http://codepad.org/MR7Dsvlz编译.

代码:

#include <iostream>

using namespace std;

int main() {
    int x = 32 ;
    // note: if x is, instead, a const int, the code still compiles, 
    // but the output is "32".

    const int * ptr1 = & x ;

    *((int *)ptr1) = 64 ; // questionable cast
    cout << x ;           // result: "64"
}
Run Code Online (Sandbox Code Playgroud)

编译时g ++是错误的吗?

Set*_*gie 9

不可以.根据C++标准的§5.4.4,可以通过C风格演员表演的演员表是:

— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast
Run Code Online (Sandbox Code Playgroud)

这被广泛称为"cast away const-ness",如果编译器没有编译该代码,编译器将不符合标准的那部分.

正如ildjarn指出的那样,const通过抛弃constness 来修改对象是未定义的行为.这个程序没有表现出未定义的行为,因为虽然指针指向const的对象,但对象本身却不是const(感谢R.Martinho和eharvest纠正我的不良阅读).

  • 诺森,你提出了相互矛盾的问题.你的标题问题的任何*是*答案都是对身体问题的答案.下次请更加小心. (3认同)