gpt4 book ai didi

c++ - 确定编译器为给定的 C 风格转换生成什么

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:08 24 4
gpt4 key购买 nike

我对 C 风格转换的理解是,编译器会运行 C++ 风格转换的各种越来越复杂/危险的排列,直到它找到一个有效的,然后默默地坚持下去。我正在工作通过代码库并将这些 C 风格的转换替换为真正的、显式的 C++ 转换。

如何确定编译器为给定的 C 风格转换生成了哪些 C++ 转换?

如果体系结构和编译器是相关的,我在 Windows 7 上使用 Visual Studio 2010(尽管我更喜欢也能识别 Linux 和 GCC 的答案)。

最佳答案

既然您无论如何都要修改代码,您可能首先要看看是否有一种方法可以重构代码以不需要强制转换。如果那证明没有结果:

  • 大多数时候,您应该使用static_cast。最常见的用法是将 void * 转换为 T *
  • 如果您试图从一个对象中删除一个const,您需要const_cast
  • 如果转换确实是在不兼容的类型之间进行的(例如,将 int 转换为指针),您将需要 reinterpret_cast

如 C++11 §5.4/4 所述,当编译器遇到强制转换符号时,它应该按照下面的方法尝试转换,直到第一个生成有效结果为止:

The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion.

...static_cast has some tweaks, see below...

If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_cast followed by a const_cast, the conversion is ill-formed.

标准表示,代表强制转换符号执行的 static_cast 稍微调整一下,即使存在非 public 继承也能正常工作。

The same semantic restrictions and behaviors apply, with the exception that in performing a static_cast in the following situations the conversion is valid even if the base class is inaccessible:
— a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
— a pointer to member of derived class type may be explicitly converted to a pointer to member of an unambiguous non-virtual base class type;
— a pointer to an object of an unambiguous non-virtual base class type, a glvalue of an unambiguous non-virtual base class type, or a pointer to member of an unambiguous non-virtual base class type may be explicitly converted to a pointer, a reference, or a pointer to member of a derived class type, respectively.

关于c++ - 确定编译器为给定的 C 风格转换生成什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com