C ++ casting

Possible duplicate:
When should static_cast, dynamic_cast, and reinterpret_cast be used?

Until a few days ago I always used C-style in C ++ because it worked well. I recently found out that using C in C ++ is very bad.

I have never used C ++ casting before, so I wonder if anyone can tell me (in their own words) what is the difference between static_cast, reinterpret_cast and const_cast?

const_cast I know that removes "const" from something, but I'm not sure what the difference is between them, and what I need to use in different situations.

+4
source share
4 answers

To say that “C casting is bad” is an extreme that is not in itself as bad as using C-style casts all the time.

Areas in which the "new" C ++ styles are to be used are: hierarchical casts (upcasts, downcasts, crosscasts), traces of const-correctness, and reinterpretation. For arithmetic castings, C-style castings work fine and do not pose any danger, so they can be safely used in C ++ code. In fact, I would recommend using C-style casts specifically as arithmetic castings - just to make arithmetic castings different from other types of translation.

+3
source

static_cast<TYPE>(e-of-TYPE2) - safe casting. This means that there is a conversion from TYPE2 to TYPE1.

reinterpret_cast is close to the C-frame, as it allows almost any conversion (with some limitations). The compiler expects you to know that type conversion is true.

The only thing that neither static_cast nor reinterpret_cast allowed is to remove the constant. I.E. if you have const char * and need to cast it to char * , this will not allow static_cast and reinterpret_cast . Instead, const_cast is your friend; const_cast used to remove the const modifier from the type.

+1
source
  • static_cast is a standard C ++ method for performing casts during compilation, when the programmer knows the type of object and / or wants to tell the compiler.
  • dynamic_cast is similar to '(T) obj' where the check is done at runtime.
  • reinterpret_cast is used to transfer between different objects without checking the runtime.
  • const_cast is explicitly converted to a type that is identical, removing constant and unstable qualifiers.
+1
source

static_cast is just c cast, for example. (INT) +1,000. it costs nothing and cannot fail. But this is only the meaning of syntactic sugar (useful for searching in the editor)

reinterpret_cast is the equivalent of C ++ (void *). It can explode in your face. Use this to tell the compiler to simply do this, and other programmers should be very careful.

dynamic_cast is a safer version that returns null if conversion is not possible. This is a small execution cost.

See also When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?

-2
source

Source: https://habr.com/ru/post/1316115/


All Articles