C++ void* to T*


In C++, void* cannot be implicitly converted to T* where T is an object type. Instead, static_cast should be used to perform the conversion explicitly. If the operand actually points to a T object, the result points to that object. Otherwise, the result is unspecified.


Even if the operand does not point to a T object, as long as the operand points to a byte whose address is properly aligned for the type T, the result of the conversion points to the same byte.

// allocating an array of 100 ints, the hard way
int* a = malloc(100*sizeof(*a));                    // error; malloc returns void*
int* a = static_cast<int*>(malloc(100*sizeof(*a))); // ok
// int* a = new int[100];                           // no cast needed
// std::vector<int> a(100);                         // better

const char c = '!';
const void* p1 = &c;
const char* p2 = p1;                           // error
const char* p3 = static_cast<const char*>(p1); // ok; p3 points to c
const int* p4 = static_cast<const int*>(p1);   // unspecified in C++03;
                                               // possibly unspecified in C++11 if
                                               // alignof(int) > alignof(char)
char* p5 = static_cast<char*>(p1);             // error: casting away constness