C++ When should we prefer to use a two chained static_cast over reinterpret_cast

reinterpret_cast should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I’M DOING. Don’t use it just out of laziness. reinterpret_cast means “treat these bits as …” Chained static casts are not the same because they may modify their targets according to the inheritence lattice. struct A { int x; … Read more

Why can’t I static_cast between char * and unsigned char *?

They are completely different types see standard: 3.9.1 Fundamental types [basic.fundamental] 1 Objects declared as characters char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value … Read more

Should I use static_cast or reinterpret_cast when casting a void* to whatever

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here. There’s a misconception that using reinterpret_cast would be a better match because it means “completely ignore type safety and just cast from A to B”. However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of … Read more

Why use static_cast(x) instead of (int)x?

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different. A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it’s a bit risky is … Read more

convert static_castmalloc/free to new/delete

Just do char* only_valid_data = new char[data_size]; to allocate. To free you do delete[] only_valid_data; Important note: When you allocate memory with new it will allocate data_size elements, not data_size bytes (like malloc does). The size of an element is the size of the non-pointer base type, in your case e.g. sizeof(*only_valid_data). In this case … Read more