memmove实现

看vector的insert方法时跟到最后有一段关于memmove的调用,总觉得不得劲,想知道它的实现

 

 看了个大佬的博客,记录一下

其中关键的三点如下:

(1)当源内存的首地址等于目标内存的首地址时,不进行任何拷贝
(2)当源内存的首地址大于目标内存的首地址时,实行正向拷贝

(3)当源内存的首地址小于目标内存的首地址时,实行反向拷贝

void* memmove(void* dest, const void* src, size_t n)
{
    char * d  = (char*) dest;
    const char * s = (const char*) src;
  
    if (s>d)
    {
         // start at beginning of s
         while (n--)
            *d++ = *s++;
    }
    else if (s<d)
    {
        // start at end of s
        d = d+n-1;
        s = s+n-1;
  
        while (n--)
           *d-- = *s--;
    }
	
    return dest;
}

  原文链接:https://blog.csdn.net/yzy1103203312/article/details/81006029

 

posted @ 2020-11-05 14:12  乐swap火  阅读(265)  评论(0编辑  收藏  举报