这个是我写的,着重于错误检查和拷贝的正确性,效率远远不如CRT的
// 考虑重叠的状况
void* _memcpy(void* dest, void* src, int len)
{
if(!dest || !src || !len || dest == src)
return dest;
char* pdest = static_cast<char*>(dest);
char* psrc = static_cast<char*>(src);
// dest 在 src + len 范围内
if(pdest > psrc && pdest < (psrc + len))
{
// 先备份被覆盖部分
int need = psrc + len - pdest;
int offset = pdest - psrc;
char* pcache = new char[need];
int i = 0;
for (i = 0; i < need; ++i)
pcache[i] = psrc[offset + i];
// 拷贝起始部分
for (i = 0; i < offset; ++i)
pdest[i] = psrc[i];
// 拷贝剩余部分
for (i = 0; i < need; ++i)
pdest[offset + i] = pcache[i];
delete[] pcache;
}
else
{
for (int i = 0; i < len; ++i)
pdest[i] = psrc[i];
}
return dest;
}
void* _memcpy(void* dest, void* src, int len)
{
if(!dest || !src || !len || dest == src)
return dest;
char* pdest = static_cast<char*>(dest);
char* psrc = static_cast<char*>(src);
// dest 在 src + len 范围内
if(pdest > psrc && pdest < (psrc + len))
{
// 先备份被覆盖部分
int need = psrc + len - pdest;
int offset = pdest - psrc;
char* pcache = new char[need];
int i = 0;
for (i = 0; i < need; ++i)
pcache[i] = psrc[offset + i];
// 拷贝起始部分
for (i = 0; i < offset; ++i)
pdest[i] = psrc[i];
// 拷贝剩余部分
for (i = 0; i < need; ++i)
pdest[offset + i] = pcache[i];
delete[] pcache;
}
else
{
for (int i = 0; i < len; ++i)
pdest[i] = psrc[i];
}
return dest;
}