C++ cast syntax styles

2019-01-01 13:22发布

A question related to Regular cast vs. static_cast vs. dynamic_cast:

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

  • C-style cast syntax: (int)foo
  • C++-style cast syntax: static_cast<int>(foo)
  • constructor syntax: int(foo)

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

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.

What do you think?

10条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 14:06

Definitely C++-style. The extra typing will help prevent you from casting when you shouldn't :-)

查看更多
还给你的自由
3楼-- · 2019-01-01 14:07

Regarding this subject, I'm following the recommandations made by Scott Meyers (More Effective C++, Item 2 : Prefer C++-style casts).

I agree that C++ style cast are verbose, but that's what I like about them : they are very easy to spot, and they make the code easier to read (which is more important than writing).

They also force you to think about what kind of cast you need, and to chose the right one, reducing the risk of mistakes. They will also help you detecting errors at compile time instead at runtime.

查看更多
其实,你不懂
4楼-- · 2019-01-01 14:07

We currently use C-style casts everywhere. I asked the other casting question, and I now see the advantage of using static_cast instead, if for no other reason than it's "greppable" (I like that term). I will probably start using that.

I don't like the C++ style; it looks too much like a function call.

查看更多
冷夜・残月
5楼-- · 2019-01-01 14:08

I use static_cast for two reasons.

  1. It's explicitly clear what's taking place. I can't read over that without realizing there's a cast going on. With C-style casts you eye can pass right over it without pause.
  2. It's easy to search for every place in my code where I'm casting.
查看更多
余生无你
6楼-- · 2019-01-01 14:08

C-style cast is the worst way to go. It's harder to see, ungreppable, conflates different actions that should not be conflated, and can't do everything that C++-style casts can do. They really should have removed C-style casts from the language.

查看更多
情到深处是孤独
7楼-- · 2019-01-01 14:09

C-style cast syntax, do not error check. C++-style cast syntax, does some checking. When using static_cast, even if it doesn't do checking, at least you know you should be carefull here.

查看更多
登录 后发表回答