Is it OK to use C-style cast for built-in types?

后端 未结 9 815
情书的邮戳
情书的邮戳 2020-12-01 16:09

After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y;

相关标签:
9条回答
  • 2020-12-01 17:02

    Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?

    Don't use them, ever. The reasons against using them applies here as well. Basically, once you use them, all bets are off because the compiler won't help you any more. While this is more dangerous for pointers than for other types, it's potentially still dangerous and gives poor compiler diagnostics in the case of errors, whereas new style casts offer richer error messages since their usage is more constrained: Meyers cites the example of casting away constness: using any cast other than const_cast won't compile, thus making it clear what happens here.

    Also, some other disadvantages apply regardless of the types, namely syntactic considerations: A C-style cast is very unobtrusive. This isn't good: C++ casts stand out clearly in the code and point to potentially dangerous code. They can also easily be searched for in IDEs and text editors. Try searching for a C-style cast in a large code and you'll see how hard this is.

    On the other hand, C-style casts offer no advantages over C++ casts so there's not even a trade-off to consider.

    More generally, Scott Meyers advises to “Minimize casts” in Effective C++ (item 27), because “casts subvert the type system.”

    0 讨论(0)
  • 2020-12-01 17:02

    If you find you need to do a C-style cast (or a reinterpret_cast) then look very carefully at your code it is 99.99% certain there is something wrong with it. Both these casts leed almost inevitably to implementation specific (and very often undefined) behaviour.

    0 讨论(0)
  • 2020-12-01 17:05

    Why do you need that particular cast? Any numeric type can be converted to a long without a cast (at potential loss of precision), so casting doesn't let the compiler do anything it can't already. By casting, all you do is remove the compiler's ability to warn if there is a potential problem. If you're converting some other basic type (like a pointer), to a long, I'd really like to see a reinterpret_cast<> rather than a C-type cast, so I can find what's going on easily if there turns out to be a problem.

    I'm not going to approve of casting without a reason, and I'm certainly not going to approve of C-type casts without a good reason. I don't see a reason to cast between most built-in types, and if there is one I want to be able to find it easily with a text search.

    0 讨论(0)
提交回复
热议问题