gpt4 book ai didi

c++ - 从(指向 const 的指针)到(指向非常量的指针)的强制转换是否无效 C++?

转载 作者:可可西里 更新时间:2023-11-01 17:35:43 24 4
gpt4 key购买 nike

我确信下面的代码不应该编译。但是,在 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"
}

编译g++是不是出错了?

最佳答案

没有。根据 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

这被广泛称为“抛弃 const-ness”,如果不编译该代码,编译器将不符合标准的该部分。

正如 ildjarn 指出的那样,通过丢弃 constness 来修改 const 对象是未定义的行为。该程序没有表现出未定义的行为,因为尽管指向const 的指针指向一个对象,但该对象本身不是const(感谢 R.Martinho 和eharvest 纠正我的错误阅读)。

关于c++ - 从(指向 const 的指针)到(指向非常量的指针)的强制转换是否无效 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8570139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com