简体   繁体   中英

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

What are the differences between

int a;
// a gets some value
double pi = static_cast<double>(a)/3;

and

int a;
// a gets some value
double pi = double(a)/3;

Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.

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

some_fun(std::string("Hello"));

Many people think they're calling a constructor there when in fact they're 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, you're 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.

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.

using static_cast is a safe C++-style way, but (double) - unsafe old C-style way.

see here: Type Casting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM