Should I really use static_cast every single time

2019-04-06 02:49发布

问题:

What makes this

long l = 1;
char c = static_cast<char>(l);

float f = 1.0f;
int i = static_cast<int>(f);

better than this

long l = 1;
char c = (char)l;

float f = 1.0f;
int i = (int)f;

when casting one primitive data type to another?

I've got much of legacy code that uses the second style for type casting in similar situations, so this is also a question about should I or may I not perform full-scale revision of that code.

回答1:

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.



回答2:

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).



回答3:

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.



回答4:

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.



回答5:

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.