温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么使用命名转换

发布时间:2021-11-26 13:55:40 来源:亿速云 阅读:146 作者:iii 栏目:大数据

本篇内容介绍了“C++怎么使用命名转换”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

ES.49:如果必须进行类型转换,使用命名转换

Reason(原因)

可读性。避免错误。命名转换比C风格转换或函数形式转换更明确,允许编译器捕捉更多错误。

The named casts are:

命名转换包括:

  • static_cast

  • 静态转换

  • const_cast

  • 常量转换

  • reinterpret_cast

  • 重新解释转换

  • dynamic_cast

  • 动态转换

  • std::move // move(x) is an rvalue reference to x

  • 移动//move(x)是x的右值引用

  • std::forward // forward<T>(x) is an rvalue or an lvalue reference to x depending on T

  • 值性转递//根据T的类型,forward<T>(x)是左值或右值引用

  • gsl::narrow_cast // narrow_cast<T>(x) is static_cast<T>(x)

  • 窄化转换//narrow_cast<T>(x)就是static_cast<T>(x)

  • gsl::narrow // narrow<T>(x) is static_cast<T>(x) if static_cast<T>(x) == x or it throws narrowing_error

  • 窄化转换(抛出异常)//如果static_cast<T>(x) == x,narrow<T>(x) 就是 static_cast<T>(x),否则抛出异常

Example(示例)
class B { /* ... */ };
class D { /* ... */ };

template<typename D> D* upcast(B* pb)
{
   D* pd0 = pb;                        // error: no implicit conversion from B* to D*
   D* pd1 = (D*)pb;                    // legal, but what is done?
   D* pd2 = static_cast<D*>(pb);       // error: D is not derived from B
   D* pd3 = reinterpret_cast<D*>(pb);  // OK: on your head be it!
   D* pd4 = dynamic_cast<D*>(pb);      // OK: return nullptr
   // ...
}

示例是从实际代码中收集的的错误集合,这段代码的前提是D过去继承于B,但有人重构了继承关系。C风格转换的危险性来自它可以是任何类型的转换,这抹杀了任何防错保护的可能性(无论是现在还是未来)。

Note(注意)

如果希望在类型之间进行无损转换(例如从float到double,或者从int32到int64),可以考虑转而使用大括号初始化。

double d {some_float};
int64_t i {some_int32};

这种方式一方面明确了类型转换的意图,另一方面可以防止转换时损失精度。(例如,在如代码所示的情况下,如果使用double值初始化float变量,会发生编译错误)

Note(注意)

reinterpret_cast can be essential, but the essential uses (e.g., turning a machine address into pointer) are not type safe:

reinterpret_cast是必不可少的,但是这种必要的用法(例如,将机器地址转换为指针)不是类型安全的。

auto p = reinterpret_cast<Device_register>(0x800);  // inherently dangerous
Enforcement(实施建议)
  • Flag C-style and functional casts.

  • 对C风格和函数形式转换进行提醒

  • The type profile bans reinterpret_cast.

  • 类型规则群组禁止reinterpret_cast.

  • The type profile warns when using static_cast between arithmetic types.

  • 类型规则群组对在算数类型之间进行转换时使用static_cast的情况进行警告。

译者注:

C风格转换:b = int(a);

函数形式转换:b=int(a);

“C++怎么使用命名转换”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI