casting – In C++, what are the differences between static_cast(a) and double(a)?

casting – In C++, what are the differences between static_cast(a) and double(a)?

Someone may have thought they were constructing rather than casting. Consider:

some_fun(std::string(Hello));

Many people think theyre calling a constructor there when in fact theyre doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.

Functional notation casts have all the same weaknesses of the other kind of C cast:

  • Can inadvertently cast away constness
  • Can silently turn into a reinterpret cast
  • Are hard to differentiate with grepping tools.

Besides all that though, youre performing exactly the same operation in both cases.

The latter is referred to as the functional notation of explicit casting where you explicitly say a should be treated as a double. You can pretty much cast anything to any type using this technique.

The former is the preferred way to cast a type in C++. It does basic checking to see that the type you are casting to makes sense (child class pointer to a base class pointer, etc.). In addition, like in the example you show, you can perform implicit conversions. Technically the static_cast in your example is explicit, but the result of the operation (the assignment) is implicit.

casting – In C++, what are the differences between static_cast(a) and double(a)?

There is no difference in terms of generated assembly code between static_cast<double> (a) and (double) a. The key advantage of cast notation, (type_id) cast_expression, is that it is more flexible. In one situation it might be the equivalent of a const_cast, in another, a static_cast, in yet another, a dynamic_cast, in yet another, a combination of const_cast and static_cast (or dynamic_cast).

This strength is also a weakness. Cast notation means different things in different places. Another disadvantage is that it is very easy to find xxx_cast<type_id> (cast_expression). Just search for _cast. It is very hard to find expressions that use cast notation.

Leave a Reply

Your email address will not be published.