简体   繁体   English

使用std :: memcpy在内存中移动对象

[英]moving an object in memory using std::memcpy

是否允许将类实例对象从一个位置移动到另一个位置(例如,通过使用std::memcpystd::memove ?假设源位置和目标位置具有相同的对齐方式。然后将目标“object”转换为源对象的类型并调用它.C ++ 11标准的哪一部分禁止这个?

You should consider the template is_trivially_copyable provided by C++11 that is useful to understand if it safe to memcpy a given type. 您应该考虑C ++ 11提供的模板is_trivially_copyable ,它有助于了解memcpy给定类型是否安全。 If the value is false then the result is undefined. 如果值为false则结果未定义。

As long as they are is_trivially_copyable , it is safe. 只要它们是可以复制的 ,它就是安全的。

§ 3.9.2 §3.9.2

For any object (other than a base-class subobject) of trivially copyable type T , whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.40 If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value. 对于普通可复制类型T的任何对象(基类子对象除外),无论对象是否保持类型T的有效值,构成对象的基础字节(1.7)都可以复制到char或者数组中。 unsigned char.40如果将char或unsigned char数组的内容复制回对象,则该对象应随后保持其原始值。

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
std::memcpy(buf, &obj, N); // between these two calls to std::memcpy,
                           // obj might be modified
std::memcpy(&obj, buf, N); // at this point, each subobject of obj of scalar type
                           // holds its original value

§ 3.9.3 §3.9.3

For any trivially copyable type T , if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes (1.7) making up obj1 are copied into obj2,41 obj2 shall subsequently hold the same value as obj1. 对于任何简单的可复制类型T ,如果指向T的两个指针指向不同的T对象obj1和obj2,其中obj1和obj2都不是基类子对象,如果构成obj1的基础字节(1.7)被复制到obj2,41 obj2中随后应保持与obj1相同的值。 [ Example: [例如:

T* t1p;
T* t2p;
    // provided that t2p points to an initialized object ...
std::memcpy(t1p, t2p, sizeof(T));
    // at this point, every subobject of trivially copyable type in *t1p contains
    // the same value as the corresponding subobject in *t2p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM