memcpy函数
#include<iostream> #include <assert.h> using namespace std; void mymemcpy(void* dst, void* src, size_t num) { assert((src != NULL) && (dst != NULL)); const char* psrc = static_cast<const char*>(src); char* pdst = static_cast<char *>(dst); ///////////////////////////////////////////////////////// //询问要求是否进行数据覆盖(深度拷贝) // //情况一: // pdst--------------------------- // psrc------------------------ // 此时为(pdst>psrc)分两种情况(1,pdst>=psrc 2,pdst<psrc) // //情况二: // pdst--------------------------------- // psrc-------------------------------- // 此时(pdst<=psrc) // //////////////////////////////////////////////////////// //情况一的第一种情况 if (pdst > psrc&&pdst < psrc + num) {//此时从后面进行复制拷贝 for (int i = num - 1;i >= 0;i--) { *(pdst + i) = *(psrc + i); } } else {//对应情况一的第二种情况 以及情况二 此时从前复制拷贝 for (int i = 0;i < num;i++) { *(pdst + i) = *(psrc + i); } } } int main() { char buf[] = "abcdefghijk"; char tmp[] = "erewer"; cout << tmp << endl; mymemcpy(tmp, buf, 5); cout << tmp << endl; system("pause"); }
优化后(int 4字节进行copy)
//优化拷贝 void mymemcpy_s(void* dst, void* src, size_t num) { assert((dst != NULL) && (src != NULL)); int wordnum = num / 4; int slice = num % 4; const int* pintsrc = static_cast<const int*>(src); int* pintdst = static_cast<int *>(dst); //copy 4bytes; //同上分两种情况 //first if (pintdst > pintsrc&&pintdst < pintsrc + num) { //copy one byte const char* pcharsrc = static_cast<const char*>(src); char* pchardst = static_cast<char *>(dst); for (int i = num - 1, j = 0;j < slice;j++, i--) { *(pchardst + i) = *(pcharsrc + i); } //copy four bytes for (int i = wordnum - 1;i >= 0;i--) { *(pintdst + i) = *(pintsrc + i); } } else {//second //copy four bytes for (int i = 0;i < wordnum;i++) { *(pintdst + i) = *(pintsrc + i); } //copy one byte const char *pcharsrc = (const char*)pintsrc; char* pchardst = (char *)(pintdst); for (int i = 0;i < slice;i++) { *pchardst++ = *pcharsrc++; } } } int main() { char buf[] = "abcdefghijk"; char tmp[] = "erewer"; cout << tmp << endl; mymemcpy_s(buf+2, buf, 5); cout << buf << endl; system("pause"); }