reinterpret_cast - 奇怪的行为

use*_*932 4 c++ casting const reinterpret-cast

我遇到了与reinterpret_cast相关的奇怪错误.看看下面的代码:

int* var;
reinterpret_cast<void const **>(&var);
Run Code Online (Sandbox Code Playgroud)

VSC++ 2010中的错误:错误C2440:'reinterpret_cast':无法从'int**'转换为'const void**'

gcc 4.1.2中的错误:从'int**'类型的reinterpret_cast到'const void**'的类型转换为constness

gcc中的错误4.6.2:从类型'int**'的reinterpret_cast到'const void**'的类型转换掉了限定符

有没有人知道为什么编译器说我正在抛弃const.我,我的几个同事都不知道它有什么问题.

感谢帮助!

Vau*_*ato 8

C++ 03标准的5.2.10节讨论了reinterpret_cast可以做什么.它明确指出"reinterpret_cast运算符不应抛弃constness".

转换constness在C++ 03标准的5.2.11节中定义.在那里使用的符号有点令人困惑,但它基本上表明如果没有给定限定的隐式转换,两种类型之间的转换"强制转换constness".

在您的情况下,您正在尝试将int **a 转换为a void const**.编译器询问"我可以隐式转换T **T const**吗?",答案是否定的,所以它说你正在抛弃constness.

这里的逻辑是reinterpret_cast用于处理更改类型,而不是更改限定符(这就是const_cast的用途).因此,如果你要求它做一些你需要const_cast的东西,它就会拒绝.