【发布时间】:2018-05-31 01:35:46
【问题描述】:
这里是Effective C++ Item 50的代码sn-p:
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);
}
为什么作者使用reinterpret_cast而不是static_cast?我可以只用reinterpret_cast 或static_cast 替换所有四个演员吗?
【问题讨论】:
-
你注意到说代码错误的评论了吗?你读过下面的解释吗?这些取消引用的指针转换需要替换为
memcpy。
标签: c++ casting type-conversion