GCC和Clang都拒绝接受以下代码中的C风格演员.
http://coliru.stacked-crooked.com/a/c6fb8797d9d96a27
struct S {
typedef const int* P;
operator P() { return nullptr; }
};
int main() {
int* p1 = const_cast<int*>(static_cast<const int*>(S{}));
int* p2 = (int*)(S{});
}
Run Code Online (Sandbox Code Playgroud)
main.cpp: In function 'int main()':
main.cpp:7:25: error: invalid cast from type 'S' to type 'int*'
int* p2 = (int*)(S{});
main.cpp:7:15: error: cannot cast from type 'S' to pointer type 'int *'
int* p2 = (int*)(S{});
^~~~~~~~~~~
但是,根据标准,C风格的演员表可以执行a static_cast后跟a 执行的转换const_cast.这段代码是否格式良好?如果没有,为什么不呢?
考虑:
float const& f = 5.9e-44f;
int const i = (int&) f;
Run Code Online (Sandbox Code Playgroud)
根据expr.cast/4这应该被视为,为了:
- 一
const_cast,- 一
static_cast,- a
static_cast后跟 aconst_cast,- 一
reinterpret_cast,或- a
reinterpret_cast后跟 aconst_cast,
显然 astatic_cast<int const&>后跟 aconst_cast<int&>是可行的,并且将导致int值为0 的 a。但是所有编译器都初始化i为42,表明它们采用了最后一个选项reinterpret_cast<int const&>后跟const_cast<int&>。为什么?
相关:在 C++ 中,C 风格的强制转换可以调用转换函数然后抛弃常量吗?,为什么 (int&)0 格式错误?, C++ 规范是否说明了如何在 static_cast/const_cast 链中选择类型以用于 C 样式强制转换?,用 (float&)int …