开发者

Are there differences between explicit type conversion "operators" in case of basic types?

Simple thing: I would like to "convert" e.g. a float into a double. Now there are three ways known to me:

float v = 4.2f;
  1. double u = (double)v;
  2. double u = double(v);
  3. double u = static_cast<double>(v);
  4. double u(v); Edit: Just thought about th开发者_高级运维is as a fourth option!

Are these identical or are there any subtle differences? What do you suggest to use?

Note that this question is only related to basic types like int, char, float, ... not to pointers, PODs or classes.


double u = (double)v; and double u = static_cast<double>(v); are equivalent because for both cases a standard conversion is used. However double u = double(v); creates a temporary double object (which can be optimized away anyway) which is then used to initialize u. But since a temporaty is created anyway, using all three kinds of casts, then yeah, it's the same.

From the three static_cast should be preferred. It's a couple of characters more typing, but in the long run it's better because first of all you explicitly specify the cast type and also since casting is generally suspicious, you do it in a very vivid manner


What about double u = v; and let the compiler do its default promotion from float to double?

If you want to explicitly show the conversion the static_cast is the preferred C++ way to do it. It's more typing but it tells the compiler precisely which conversion you want to happen.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜