无效到 T.

在 C++中,void*不能隐式转换为 T*,其中 T 是一个对象类型。相反,static_cast 应该用于显式执行转换。如果操作数实际指向 T 对象,则结果指向该对象。否则,结果未指定。

Version >= C++ 11

即使操作数不指向 T 对象,只要操作数指向一个字节,其地址与 T 类型正确对齐,转换结果指向同一个字节。

// 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