首页 文章

在C中,C风格的演员可以调用转换函数然后抛弃constness吗?

提问于
浏览
27

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 回答

  • 9

    这是core issue 909

    根据5.4 [expr.cast]第4段,对旧式演员的一种可能的解释是static_cast,然后是const_cast . 因此,可以预期在以下示例中标记为#1和#2的表达式将具有相同的有效性和含义:struct S {
    operator const int *();
    };

    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解决过 . 是时候打开门票了 .

相关问题