我想了解的区别memcpy()和memmove(),和我读的文本memcpy(),而没有照顾重叠源和目的地memmove()一样.
但是,当我在重叠的内存块上执行这两个函数时,它们都会给出相同的结果.例如,在memmove()帮助页面上采用以下MSDN示例: -
有没有更好的例子来理解它的缺点memcpy和memmove解决方法?
// crt_memcpy.c
// Illustrate overlapping copy: memmove always handles it correctly; memcpy may handle
// it correctly.
#include <memory.h>
#include <string.h>
#include <stdio.h>
char str1[7] = "aabbcc";
int main( void )
{
printf( "The string: %s\n", str1 );
memcpy( str1 + 2, str1, 4 );
printf( "New string: %s\n", str1 );
strcpy_s( str1, sizeof(str1), "aabbcc" ); // reset string
printf( "The string: …Run Code Online (Sandbox Code Playgroud) 一个同事想写这个:
std::string_view strip_whitespace(std::string_view sv);
std::string line = "hello ";
line = strip_whitespace(line);
Run Code Online (Sandbox Code Playgroud)
我说返回string_view让我先验地感到不安,而且,这里的别名对我来说看起来像 UB。
我可以肯定地说,line = strip_whitespace(line)在这种情况下相当于line = std::string_view(line.data(), 5). 我相信会调用string::operator=(const T&) [with T=string_view],其定义为等价于line.assign(const T&) [with T=string_view],其定义为等价于line.assign(line.data(), 5),其定义为:
Preconditions: [s, s + n) is a valid range.
Effects: Replaces the string controlled by *this with a copy of the range [s, s + n).
Returns: *this.
Run Code Online (Sandbox Code Playgroud)
但这并没有说明出现混叠时会发生什么。
我昨天在 cpplang Slack 上问了这个问题,得到的答案喜忧参半。在这里寻找超级权威的答案,和/或对真实图书馆供应商实施的实证分析。
我写测试用例了string::assign,vector::assign …