在什么条件下使用std :: memcpy在对象之间进行复制是安全的? [英] Under what conditions is it safe to use std::memcpy to copy between objects?
问题描述
在什么条件下使用std::memcpy
从一个对象复制到另一个对象是否安全?
Under what set of conditions is it safe to use std::memcpy
to copy from one object to another?
例如,为了使以下内容安全,T
,src
和dest
必须满足哪些条件:
For example, what conditions must T
, src
and dest
satisfy for the following to be safe:
template <typename T>
void copy_bytewise(T& dest, const T& src) {
std::memcpy(&dest, &src, sizeof(T));
}
我们唯一可以假设的关于src
和dest
的地方是它们不重叠 1 .特别是src
或dest
之一可能是对成员或基类的引用.
The only thing we can assume about src
and dest
is that they don't overlap1. In particular either of src
or dest
may be a reference to a member or base class.
我对涉及该标准的答案很感兴趣,但是如果这与常规做法(例如,来自Itanium的事实上的C ++ ABI)有所不同,我也想知道.
I am interested in answers which refer to the standard, but if this diverges from common practice (e.g., the de-facto C++ ABI from Itanium) I'd also like to know.
请注意,T
满足 TriviallyCopyable (TC)概念是不够的,如此示例所示. base
是TC,但不是memcpy安全的(由于对派生类的成员重复使用填充).
Note that T
satisfying the TriviallyCopyable (TC) concept is not sufficient, as this example shows. base
is TC yet not memcpy-safe (due to re-use of padding for members of a derived class).
我特别感兴趣的是,仅在T
上有任何任何条件就足够了(但不一定是必要的),而又没有src
和dest
上的条件(在通常是静态确定的.
I am especially interested if there is any condition on T
alone that is sufficient (and not necessarily necessary), without requiring conditions on src
and dest
(that cannot, in general, be statically determined).
1 具体来说,我的假设是,如果它们 do 重叠,则它们仍然可以在与std::memcpy
相同的条件下在T
上进行安全复制,但是使用std::memmove
代替.如果假设不正确,则可能是答案的一部分.
1 Specifically, my assumption is that if they do overlap, they are still safe to copy under the same conditions on T
as for std::memcpy
, but using std::memmove
instead. If assumption is incorrect, it could be part of an answer.