-2

Should be prefer reinterpret_cast over C style casting. Please explain.

Which one should be preferred if one has to choose between reinterpret_cast and c style casting

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Consider removing tag c and adding tag c++. – V. Kravchenko Jan 15 '16 at 06:56
  • It's like trying to pick the lesser of two evils. If you *need* it (like when e.g. calling [`istream::read`](http://en.cppreference.com/w/cpp/io/basic_istream/read)) then you should prefer `reinterpret_cast`, but in almost all other cases I would say that if you need to do such a cast you're doing something wrong. Casting like that is definitely a [*code smell*](https://en.wikipedia.org/wiki/Code_smell). – Some programmer dude Jan 15 '16 at 07:01

2 Answers2

2

Casts should be used rarely, and cautiously, and it is a lot easier to spot when you're abusing the system if you write:

char *x = const_cast<char *>(some_const_char_pointer_expression);

than if you disguise it with:

char *x = (char *)some_const_char_pointer_expression;

So, use the explicit, controlled, verbose notation because it encourages you to avoid casts, and to use the correct, precise cast when you must use one.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    You might find this interesting: https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-lee.pdf It's about a "bad-casting" detection tool [CaVer]. In addition to the basic function as outlined in the paper, it would be interesting to see if CaVer's implementation of RTTI-like data [used by it internally] could be adapted so that it could be used as a [faster] alternative to the conventional [string based] RTTI information – Craig Estey Jan 15 '16 at 08:00
0

C style cast is more general. It 'chooses' from const_cast, static_cast, const_cast with static_cast, dynamic_cast, then dynamic_cast with const_cast and finally reinterpret_cast, reinterpret_cast with const_cast. So, as you see, there is pretty much difference between c-cast and reinterpret_cast, as C-cast cast goes with static and dynamic cast first.

If you write in C++, you should prefer one of casts above instead of C-style cast. They are more explicit. But C-style cast is not a very-very-very bad style.

V. Kravchenko
  • 1,859
  • 10
  • 12