無效到 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