复制琐碎的可复制对象是否始终在C ++ 14中定义? [英] Is copying trivially copyable objects always defined in C++14?
本文介绍了复制琐碎的可复制对象是否始终在C ++ 14中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于 容易复制 类型T,请考虑:
For a trivially copyable type T consider:
void f(T z)
{
T a;
T b;
std::memcpy(&b, &a, sizeof(T));
a = z;
b = z;
// ...
}
是行为如果
- T为char,
- T为int,则在C ++ 14中定义,或者
- T是struct {int data; }; ?
假定 f
被传递了一个持有有效值的对象。
Assume that f
gets passed an object that holds a valid value.
如果对 memcpy
的调用被副本分配 b = a
?
结果可以结转到复制结构 T(a)
和移动施工/布置?
注意:与什么是聚合和POD以及它们为什么/为什么有区别? / a>,尤其关注复制不确定值的特殊情况。
推荐答案
此处有几件事情起作用:
There are a couple things at play here:
- 计算为不确定值的表达式会导致未定义的行为,但有某些例外情况(8.5p12)
-
未签名的字符
(如果未签名,则可能是char
) - 具有自动存储持续时间并且类型具有默认初始化的变量,最初具有不确定的值(5.3.4p17)
- an expression evaluating to an indeterminate value causes undefined behavior, with certain exceptions (8.5p12)
unsigned char
(and possiblychar
, if unsigned) is the exception- variables with automatic storage duration and whose types have trivial default initialization initially have indeterminate values (5.3.4p17)
这意味着
-
未签名字符
是可以的,否是否使用memcpy
或memmove
或复制分配或复制构造器 -
memcpy
和memmove
可能对所有类型都适用,因为结果不是通过评估产生的(满足此要求,实现可以在内部使用unsigned char
,或利用对其他类型的实现特定的保证) - 复制如果右侧是不确定的值,其他类型的构造函数和复制分配将失败
unsigned char
is fine, no matter whether usingmemcpy
ormemmove
or copy-assignment or copy-constructormemcpy
andmemmove
is presumably fine for all types, because the result is not "produced by an evaluation" (to meet this requirement, an implementation can useunsigned char
internally, or take advantage of implementation-specific guarantees made for other types)- copy-constructor and copy-assignment for other types will fail if the right-hand-side is an indeterminate value
当然,即使复制不确定值的有效方法会创建另一个不确定值。
Of course, even the valid methods for copying an indeterminate value create another indeterminate value.
段数字对应于草案n4527
Paragraph numbers correspond to draft n4527
这篇关于复制琐碎的可复制对象是否始终在C ++ 14中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文