在什么条件下使用std :: memcpy在对象之间进行复制是安全的? [英] Under what conditions is it safe to use std::memcpy to copy between objects?

查看:406
本文介绍了在什么条件下使用std :: memcpy在对象之间进行复制是安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么条件下使用std::memcpy从一个对象复制到另一个对象是否安全?

Under what set of conditions is it safe to use std::memcpy to copy from one object to another?

例如,为了使以下内容安全,Tsrcdest必须满足哪些条件:

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));
}

我们唯一可以假设的关于srcdest的地方是它们不重叠 1 .特别是srcdest之一可能是对成员或基类的引用.

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上有任何任何条件就足够了(但不一定是必要的),而又没有srcdest上的条件(在通常是静态确定的.

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.

推荐答案

来自

对于任何普通可复制类型T,如果两个指向T的指针指向不同的T对象obj1obj2,其中obj1obj2都不是基类子对象,如果将构成obj1的基础字节([intro.memory])复制到obj2,则obj2随后应保持与obj1相同的值.

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 ([intro.memory]) making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.

简而言之:

为了使以下内容安全,必须满足哪些条件

what conditions must T satisfy for the following to be safe

T必须是可复制的;这是T必须满足的唯一条件.另一个要求不是对T的限制,而是对可能要复制的对象的性质的限制.这意味着您无法静态确定.

T must be trivially copyable; that's the only condition that T must satisfy. The other requirement is not a restriction on T, but a restriction on the nature of the objects potentially being copied. Which means it's not something you can statically determine.

这篇关于在什么条件下使用std :: memcpy在对象之间进行复制是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆