Should I really use static_cast every single time I want to convert between primitive types?

好久不见. 提交于 2019-12-04 02:52:41
R. Martinho Fernandes

Future-proofing.

Let's say in the future I do this:

float blah = 1.0f;
float* f = &blah;

Now, int i = static_cast<int>(f); stops compiling, but int i = (int)f; does a reinterpret_cast.

static_cast<int> is this is exactly what I want you to do. (int) is do whatever you can to get me an int. With the latter, the compiler will go out of its way to get you an int value, and that's rarely (never?) desirable.

JohnMcG

The every single time is a bit of an indication.

You shouldn't be converting between primitive types so often that typing a few extra characters each time is an overly onerous task. It's kind of like complaining that you have to wear a helmet every time you do some dangerous activity. If you're finding wearing the helmet too annoying, the problem is likely that you're engaging in dangerous activity too often rather than the helmet requirement.

As for addressing legacy code, you can check out this question for some answers (including my own).

Yes, you should.

Casts are a major source of bugs. They are ways around the type-system, which is one of the best bug catchers available to programmers.

A static_cast is much more visible and much more specific than an old c-style cast. You want them to stand out. You want them to be obvious when you're debugging. You want the next programmer to come along to understand why you're doing it.

The fact that it's harder to type static_cast<blah>(foo) is also a benefit, as it'll encourage you to cast only when absolutely necessary.

A constructor cast is an alternative. Assuming there is a conversion constructor defined. For example:

int i(0);
float f(3.14F);
i = int(f);

However you should definitely prefer static_cast and other C++ casts over a C-style cast as those basically say "try every cast until something works" which will eventually hit the equivalent of a reinterpret_cast and probably give you incorrect behavior.

The issue with C-style casts is that it -may let you do conversions you didn't intend.

It is something you should do in the future but I wouldn't go back and change it unless you do find an issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!