我很难理解为什么不允许使用 memcpy'ing non_copyable 类型,或者即使我的以下代码是不允许的:
struct trivially_copyable_type
{
int member;
};
struct non_trivially_copyable_type
{
int member;
non_trivially_copyable_type() { }
non_trivially_copyable_type(const non_trivially_copyable_type& other) { }
};
int main()
{
bool result = std::is_trivially_copyable_v<trivially_copyable_type>; // True
result = std::is_trivially_copyable_v<non_trivially_copyable_type>; // False
trivially_copyable_type copyable;
void* memory = malloc(128);
memcpy(memory, ©able, sizeof(copyable));
trivially_copyable_type* p1 = (trivially_copyable_type*)memory;
p1->member = 7; // This is allowed
non_trivially_copyable_type noncopyable;
memcpy(memory, &noncopyable, sizeof(noncopyable));
non_trivially_copyable_type* p2 = (non_trivially_copyable_type*) memory;
p2->member = 7; // This is undefined or illegal?
}
如果我们 malloc 内存并通过指向 int 的指针访问该内存,如下所示:
int * ptr = (int*) malloc(128);
*ptr = 7; // We didn't create an int, but can treat that memory as int
以同样的方式:
trivially_copyable_type* ptr = (trivially_copyable_t*) malloc(128);
*ptr = 7; // Same, we didn't create a 'trivially_copyable_type object at memory, but can read and write to it
但:
non_trivially_copyable_type* ptr = (non_trivially_copyable_t*) malloc(128);
*ptr = 7; // Is whether this is legal dependent on whether the type is trivially_constructible or not?
我不明白为什么或者如果在前面的例子中我 memcpy 进入缓冲区是非法的。