从(指向 const 的指针)到(指向非 const 的指针)的强制转换是否无效 c++?
我确信以下代码不应编译。但是,在 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++编译这个有错误吗?
I am sure that the following code should not compile. But, in g++, it does compile! See it compile at http://codepad.org/MR7Dsvlz .
The code:
#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"
}
Is g++ in error by compiling this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以。根据 C++ 标准的 §5.4.4,C 风格强制转换可以执行的强制转换为:
这被广泛称为“强制转换
const
-ness”,并且编译器如果不编译该代码,则将不符合该标准的该部分。正如 ildjarn 指出的那样,通过放弃 const 性来修改 const 对象是未定义的行为。该程序不会表现出未定义的行为,因为尽管指针指向 const 对象,但该对象本身不是 const(感谢 R.Martinho 和eharvest 纠正我的错误阅读)。
No. According to §5.4.4 of the C++ standard, the casts that can be performed by a C-style cast are:
This is widely known as "casting away
const
-ness", and the compiler would be non-conformant to that part of the standard if it did not compile that code.As ildjarn points out, modifying a
const
object via casting awayconst
ness is undefined behaviour. This program does not exhibit undefined behaviour because, although an object that was pointed to by the pointer-to-const
, the object itself is notconst
(thanks R.Martinho and eharvest for correcting my bad reading).不会。编译代码时 g++ 不会出错。你所做的演员表是有效的。
(int *)ptr1
是 ac 类型转换。 C++ 中的等效项是const_cast(ptr1)
。第二种风格读起来更清晰。但是,需要执行此转换(修改 const 变量)显示了设计中的问题。
No. g++ is not in error by compiling your code. the cast you have done is valid.
(int *)ptr1
is a c cast. the equivalent in c++ isconst_cast<int*>(ptr1)
. the second style is clearer to read.but, the need to do this cast (to modify a const variable) shows a problem in the design.
*((int *)ptr1) = 64
行相当于*(const_cast(ptr1)) = 64
code> 是使用强制转换符号时执行的第一个强制转换。The line
*((int *)ptr1) = 64
is equivalent to*(const_cast<int*>(ptr1)) = 64
Theconst_cast
is the first cast that is performed when you use the cast notation.