What is static_cast for, how does it work and where is it used?
- oneru.wikipedia.org/wiki/… - b2soft
1 answer
static_cast has a lot of different uses. His idea is this: this is a limited-power C-style cast. Restriction is necessary because the C-style cast can lead anything to anything (well, almost), and thus can hide the error. For example, you can randomly cast const char* in char* , getting crash on some systems with hardware support for const memory. static_cast won't let you do this.
Most of the time, when you want to do an explicit type conversion (and I hope this happens quite rarely), you want exactly static_cast .
The formal list of everything that static_cast can static_cast is very large , I will give only the most important things that he can (and also he can't ):
What can:
- Convert pointer to parent class to pointer to child class. The object by pointer must be the correct child class, otherwise undefined behavior. If you are unsure and want to check if the object is a subclass of the object, use
dynamic_cast(it is designed specifically for this). - Conversions between numeric types.
int,long,char,unsigned int- all of them can be cast into each other with the help ofstatic_cast. - You can cast any expression in
void. The result will be calculated and discarded (but the side effects will, of course, be fulfilled). static_castcan cast thenullptrconstant to any pointer type. This is usually not necessary and you can rely on implicit type conversion, but sometimes (for example, to select the desired function overload) this can be useful.
What can not:
- Conversion between pointers to basically incompatible types. For example, a pointer to a
doublecannot be cast to a pointer to anint. For type safety tricks, usereinterpret_cast. - Pointers to types, as well as the types themselves with incompatible
constand / orvolatileattributes. If you need to break const-correctness, useconst_cast. - Of course, you cannot cast a pointer to a member function to a pointer to a regular function, or a pointer to a code to a pointer to data. For these dirty hacks, use
reinterpret_cast.
Another reason to use static_cast (as well as other C ++ specific type conversions) is the ease with which it can be searched in the source code, both with the eyes and with the search utilities. Cinnamon caste (especially its functional variety) is very easy to miss in the code.
For comparison, the “usual” type conversion (C-style cast) is equivalent to the following sequence:
const_cast.- If
const_castcannot give the desired result, thenstatic_cast(but with an allowed conversion to the undeclared type) - If this does not work out, then the compiler tries to add
const_castto thestatic_castconst_cast. - If this fails, then
reinterpret_cast. - ... and if it fails, then
const_castappended to it.
- @VladD thank you very much, perhaps, I will refer to this answer repeatedly. Very little understandable article seems. - perfect
- @perfect: Please! - VladD