C++ 强制转换语法样式 [英] C++ cast syntax styles

查看:23
本文介绍了C++ 强制转换语法样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个关于常规转换 vs. static_cast vs. dynamic_cast 的问题:

您更喜欢 C++ 中的哪种强制转换语法风格?

What cast syntax style do you prefer in C++?

  • C 风格的强制转换语法:(int)foo
  • C++ 风格的强制转换语法:static_cast(foo)
  • 构造器语法:int(foo)

它们可能不会翻译成完全相同的指令(是吗?)但它们的效果应该是相同的(对吧?).

They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).

如果您只是在内置数字类型之间进行转换,我会发现 C++ 风格的转换语法过于冗长.作为一名前 Java 程序员,我倾向于使用 C 风格的强制转换语法,但我当地的 C++ 大师坚持使用构造函数语法.

If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.

你怎么看?

推荐答案

最佳实践从不使用 C 风格的强制转换主要有以下三个原因:

It's best practice never to use C-style casts for three main reasons:

  • 如前所述,这里不执行检查.程序员根本不知道使用了削弱强类型的各种强制转换中的哪一个
  • 新的演员阵容有意在视觉上引人注目.由于强制转换通常会暴露代码中的弱点,因此有人认为在代码中显示强制转换是一件好事.
  • 如果使用自动化工具搜索演员表,则尤其如此.几乎不可能可靠地找到 C 风格的强制转换.

正如 palm3D 指出的那样:

As palm3D noted:

我发现 C++ 风格的强制转换语法过于冗长.

I find C++-style cast syntax too verbose.

出于上述原因,这是故意的.

This is intentional, for the reasons given above.

构造函数语法(正式名称:函数风格的强制转换)在语义上与 C 风格的强制转换相同,也应该避免(声明时的变量初始化除外),因为相同原因.即使对于定义了自定义构造函数的类型,但在 Effective C++ 中,这是否也应该是有争议的,Meyers 认为即使在这些情况下,您也应该避免使用它们.举例说明:

The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:

void f(auto_ptr<int> x);

f(static_cast<auto_ptr<int> >(new int(5))); // GOOD
f(auto_ptr<int>(new int(5));                // BAD

这里的 static_cast 实际上会调用 auto_ptr 构造函数.

The static_cast here will actually call the auto_ptr constructor.

这篇关于C++ 强制转换语法样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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