标准定义我们可以通过以下方式使用 std::memcpy int:
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.
如果我们将该函数应用于非平凡可复制类型的对象,我们可能会遇到什么潜在问题?以下代码的工作方式就好像它适用于平凡可复制的类型:
#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
的问题。
#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;
}
关于c++ - 将 std::memcpy 用于非平凡可复制类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26030873/