Const_ cast,static_ cast, dynamic_ cast, reinterpret_ cast

  1. const_ Cast: used to convert const variables to non const variables
int n = 5;
int *k1 = const_ Cast (& n); // pointer
*k1 = 1;
int &k2 = const_ Cast (n); // reference
k2 = 2;
const int a = 10;
int* b = const_cast(&a);
*B = 11; // the attribute of pointer B becomes readable and writable

  2. Static cast: it has two functions, one is to replace implicit conversion, the other is to replace conversion between derived classes of base class

2.1) implicit conversion

int n = 10;
char c = 'a';
void *p = nullptr;
int *k = static_cast(p);
n = static_ Cast (c); // N becomes 97. The position of character a in the ascll code is equivalent to int n = (int) C;

2.2) conversion between derived classes of base class: it is safe to convert derived classes to base classes, but not vice versa, because derived classes expand many other methods. static_ Cast does not provide security checks.

  3. dynamic_ Cast: mainly used for conversion between derived classes of base class, providing security check, and usually base class should contain virtual function.

Note: it can be divided into two types: pointer type dynamic_ Cast and dynamic of reference type_ Cast type conversion. If the conversion fails, the pointer type will return 0 and the reference type will return bad_ cast。

  4. reinterpret_ Cast: almost everything can be turned, such as turning int to pointer, which may cause problems. Try to use it as little as possible.


reference resources:

  1.    Niuke C + + interview dictionary Chapter 2 Section 1.

  2.    There are four cast casts in C + +.

Recommended Today

How to use JWT, titles, kicks, and force users to exit?

As the most popular cross domain authentication scheme, JSON web token (JWT) is familiar to everyone. Many systems are using JWT instead of session authentication. What’s the difference between the two?In short, JWT saves the authenticated data in the client and session in the server.After using JWT instead of session authentication, the server does not […]