将 std::memcpy 用于非平凡可复制类型的对象 [英] Using std::memcpy to object of non-trivially copyable type
问题描述
标准定义我们可以通过以下方式使用 std::memcpy int :
The standard defines we can use std::memcpy int the following way:
对于任何可简单复制的类型 T,如果两个指向 T 的指针指向不同的 T 对象 obj1 和 obj2,其中 obj1 和 obj2 都不是基类子对象,如果构成 obj1 的底层字节 (1.7) 是复制到 obj2 中,obj2 随后将保持与 obj1 相同的值.
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, obj2 shall subsequently hold the same value as obj1.
如果我们将该函数应用于非平凡可复制类型的对象,我们可能会遇到什么潜在问题?下面的代码就好像它适用于可简单复制的类型一样:
What potential problem we could get if we applied that function to an object of non-trivially copyable type? The following code works as if it worked for trivially-copyable type:
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
struct X
{
int a = 6;
X(){ }
X(const X&)
{
cout << "X()" << endl;
}
};
X a;
X b;
int main()
{
a.a = 10;
std::memcpy(&b, &a, sizeof(X));
cout << b.a << endl; //10
}
推荐答案
你问:
如果我们将该函数应用于非平凡可复制类型的对象,我们可能会遇到什么潜在问题?
What potential problem we could get if we applied that function to an object of non-trivially copyable type?
这是一个非常简单的例子,它说明了将 std::memcpy
用于非平凡可复制类型的对象的问题.
Here's a very simple example that illustrates the problem of using std::memcpy
for objects of non-trivially copyable type.
#include <cstring>
struct A
{
A(int size) : size_(size), data_(new int[size]) {}
~A() { delete [] data_; }
// The copy constructor and the copy assignment operator need
// to be implemented for the class too. They have been omitted
// to keep the code here minimal.
int size_;
int* data_;
};
int main()
{
A a1(10);
A a2(20);
std::memcpy(&a1, &a2, sizeof(A));
// When we return from the function, the original data_ of a1
// is a memory leak. The data_ of a2 is deleted twice.
return 0;
}
这篇关于将 std::memcpy 用于非平凡可复制类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!