本文介绍了在C ++中,C风格的cast是否可以调用转换函数,然后丢弃constness?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC和Clang都拒绝以下代码中的C风格投射。



  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:在函数'int main ()':
main.cpp:7:25:error:invalid从类型'S'到类型'int *'
int * p2 =(int *)(S {})
main.cpp:7:15:错误:无法从类型'S'转换为指针类型'int *'
int * p2 =(int *)(S {});
^ ~~~~~~~~~~~

但是,根据标准,C风格的执行由 static_cast 后跟 const_cast 执行的转换。这段代码是否格式良好?

解决方案

这是:

这显然从来没有解决由Clang或GCC。打开票证的时间。


GCC and Clang both reject the C-style cast in the following code.

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{});
              ^~~~~~~~~~~

However, according to the standard, a C-style cast can perform the conversions performed by a static_cast followed by a const_cast. Is this code well-formed? If not, why not?

解决方案

This is core issue 909:

This was apparently never resolved by neither Clang nor GCC. Time to open tickets.

这篇关于在C ++中,C风格的cast是否可以调用转换函数,然后丢弃constness?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 17:38