[英]When we should use a memcpy and memmove in c++?
I reflecting about memcpy. 我在反思memcpy。
I know that memcpy is for copy a variable to variable. 我知道memcpy是用于将变量复制到变量。
But it is not better to use: (for ex.) 但最好不要使用:( 例如)
int a = 5;
int b;
b = a;
Instead memcpy ? 而是memcpy吗?
or use std::move
instead memmove
? 或使用
std::move
代替memmove
吗?
Memcpy
and Memmove
are not outdated/slowly functions (perhaps these functions are from C)? Memcpy
和Memmove
没有过时/慢慢功能(也许这些功能是从C)? In order of decreasing importance, advantages are: 按重要性递减的顺序,优点是:
memcpy
and memmove
are type agnostic, so they can be used to bypass strict aliasing restrictions. memcpy
和memmove
与类型无关,因此可用于绕过严格的别名限制。
memcpy
and memmove
don't require alignment, although they probably run faster when data is aligned. memcpy
和memmove
不需要对齐,尽管对齐数据时它们可能运行得更快。
memcpy
may be faster, since it can copy multiple elements at once. memcpy
可能会更快,因为它可以一次复制多个元素。 With the std::is_trivially_copyable
type trait, though, std::copy
should do this also. 但是,对于
std::is_trivially_copyable
类型特征, std::copy
应该这样做。
Of course, they have the disadvantage of only working with trivially copyable types, and only with pointers, not iterators. 当然,它们的缺点是只能使用普通可复制的类型,并且只能使用指针而不是迭代器。 But they have definite uses in C++ code, for example when pulling unaligned data out of network packets or blocks of files, or implementing approximations to floating-point functions using bit tricks .
但是它们在C ++代码中有明确的用途,例如,当从网络数据包或文件块中拉出未对齐的数据时,或使用位技巧来实现浮点函数的近似值时 。
You are only considering one case. 您仅考虑一种情况。 Nobody use
memcpy
and memmove
for int
variables. 没有人将
memcpy
和memmove
用于int
变量。
They are basically highly optimized function to copy large blocks of data. 它们基本上是高度优化的功能,可以复制大块数据。 They are the system functions.
它们是系统功能。 They directly deal with memory.
它们直接处理内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.