Here is a code snippet of Effective C++ Item 50:
static const int signature = 0xDEADBEEF;
typedef unsigned char Byte;
// this code has several flaws — see below
void* operator new(std::size_t size) throw(std::bad_alloc)
{
using namespace std;
size_t realSize = size + 2 * sizeof(int); // increase size of request so 2
// signatures will also fit inside
void *pMem = malloc(realSize); // call malloc to get the actual
if (!pMem) throw bad_alloc(); // memory
// write signature into first and last parts of the memory
*(static_cast<int*>(pMem)) = signature;
*(reinterpret_cast<int*>(static_cast<Byte*>(pMem)+realSize-sizeof(int))) = signature;
// return a pointer to the memory just past the first signature
return static_cast<Byte*>(pMem) + sizeof(int);
}
Why did the author use reinterpret_cast
instead of static_cast
? Can I replace all the four casts only with reinterpret_cast
or static_cast
?
Why did the author use
reinterpret_cast
instead ofstatic_cast
?
static_cast
could convert pointer type to void*
and convert it back, but it can't convert between pointer to unrelated types. reinterpret_cast
could.
5) Any pointer to object of type T1 can be converted to pointer to object of another type cv T2. This is exactly equivalent to
static_cast<cv T2*>(static_cast<cv void*>(expression))
(which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below)
User contributions licensed under CC BY-SA 3.0