本文介绍了为什么std :: memcpy的行为对于不是TriviallyCopyable的对象是未定义的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从:

在我的工作中,我们使用 std :: memcpy 很长时间不使用TriviallyCopyable的位交换对象:

At my work, we have used std::memcpy for a long time to bitwise swap objects that are not TriviallyCopyable using:

void swapMemory(Entity* ePtr1, Entity* ePtr2)
{
   static const int size = sizeof(Entity); 
   char swapBuffer[size];

   memcpy(swapBuffer, ePtr1, size);
   memcpy(ePtr1, ePtr2, size);
   memcpy(ePtr2, swapBuffer, size);
}

,从未出现任何问题。

我理解,对非TriviallyCopyable对象滥用 std :: memcpy 并导致下游未定义的行为是微不足道的。但是,我的问题:

I understand that it is trivial to abuse std::memcpy with non-TriviallyCopyable objects and cause undefined behavior downstream. However, my question:

为什么 std :: memcpy TriviallyCopyable对象?为什么标准认为有必要指定?

Why would the behavior of std::memcpy itself be undefined when used with non-TriviallyCopyable objects? Why does the standard deem it necessary to specify that?

UPDATE

已被修改,以响应原始帖子和帖子的答案。当前描述为:

It turns out that the standard does not say anything about the behavior of std::memcpy for objects that are not TriviallyCopyable. The contents of http://en.cppreference.com/w/cpp/string/byte/memcpy have been modified in response to the original post and the answers to the post. The current description says:

这篇关于为什么std :: memcpy的行为对于不是TriviallyCopyable的对象是未定义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:31