c++ - 将 std::memcpy 用于非平凡可复制类型的对象

标签 c++ types

标准定义我们可以通过以下方式使用 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
}

DEMO

最佳答案

你问:

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/

相关文章:

c++ - MFC面板和窗口句柄

c++ - 分配语法与λ微积分应用语法冲突

c# - 引用类型是一个对象?

c - 解释这个 gcc 函数的类型化行为

c# 如何将泛型类型参数转换并传递给内部函数?

c++ - 如何使用所需的 BSTR* 参数正确调用 IDispatch::Invoke

c++ - 如果使用 delete 释放使用 malloc() 获得的内存,是否应该产生警告甚至断言失败?

c++ - 对 boost asio 完成处理程序的右值引用

c++ - Perl Win32::API 和指针

.net - Type和TypeInfo有什么区别或关系?