在C ++中,C风格的cast是否可以调用转换函数,然后丢弃constness? [英] In C++, can a C-style cast invoke a conversion function and then cast away constness?

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

问题描述

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:在函数'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 执行的转换。这段代码是否格式良好?

解决方案

这是核心问题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))
pre>

原理(2009年7月)



的措辞,示例应该工作。这似乎只是一个编译器错误。


这显然从来没有解决由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:

According to 5.4 [expr.cast] paragraph 4, one possible interpretation of an old-style cast is as a static_cast followed by a const_cast. One would therefore expect that the expressions marked #1 and #2 in the following example would have the same validity and meaning:

struct S {
  operator const int* ();
};

void f(S& s)  {
  const_cast<int*>(static_cast<const int*>(s));  // #1
  (int*) s;  // #2
}

However, a number of implementations issue an error on #2.

Is the intent that (T*)x should be interpreted as something like

const_cast<T*>(static_cast<const volatile T*>(x))

Rationale (July, 2009):

According to the straightforward interpretation of the wording, the example should work. This appears to be just a compiler bug.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆