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{});
}
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风格的强制转换可以执行 static_cast
后跟 const_cast
执行的转换 . 这段代码是否格式良好?如果没有,为什么不呢?
1 回答
这是core issue 909:
void f(S&s){
const_cast <int *>(static_cast <const int *>(s)); //#1
(int *)s; //#2
}
但是,许多实现在#2上发出错误 . 意图是(T *)x应该被解释为类似const_cast <T *>(static_cast <const volatile T *>(x))
理由(2009年7月):根据对措辞的直截了当的解释,这个例子应该有效 . 这似乎只是一个编译器错误 .
这显然从未被Clang和GCC解决过 . 是时候打开门票了 .