[英]std::is_trivially_copyable requirements
The c++ standard (and several SO answers ) states that to qualify as is_trivially_copyable<T>
, a type T
must have: c ++标准(和几个SO 答案 )指出,要符合
is_trivially_copyable<T>
,类型T
必须具有:
(These are not the only requirements, but the question focuses on these alone) (这些不是唯一的要求,但是问题只针对这些要求)
Can someone shed any light on why ? 有人可以解释为什么吗? I don't see how violating any of these 3 makes an array of
T
's unsafe for memcpy. 我看不到违反这3个因素如何使
T
数组对memcpy不安全。
With regard to 1 ("a default destructor"), it's simply because memcpy
of a new object into an existing variable won't call the destructor of what it's overwriting, so if the class depends on anything in that destructor, its constraints may be violated. 关于1(“默认析构函数”),仅是因为将新对象的
memcpy
转换为现有变量不会调用其覆盖的析构函数,因此,如果类依赖于该析构函数中的任何内容,则其约束可能是侵犯。
With regard to 2 ("no virtual functions"), it's likely that the reasoning is that when object slicing occurs, the sliced object must function correctly as the base class object. 对于2(“无虚函数”),可能的原因是当发生对象切片时,切片的对象必须正确地充当基类对象。
Imagine a base and a derived class thus: 想象一下这样的基类和派生类:
class Base {
int b;
virtual void f() { ++b; }
}
class Derived : public Base {
int d;
void f() override { ++d; }
}
Now suppose you have a Base&
variable v
that actually references a Derived
object. 现在假设您有一个
Base&
变量v
,它实际上引用了Derived
对象。 If std::is_trivially_copyable<Base>
were true, you could memcpy
from this variable to another Base
object w
(this would copy b
and the vtable
). 如果
std::is_trivially_copyable<Base>
为true,则可以将此变量从memcpy
转移到另一个Base
对象w
(这将复制b
和vtable
)。 If you were now to call wf()
, you would call (through the vtable) Derived::f()
. 如果现在要调用
wf()
,则可以(通过vtable)调用Derived::f()
。 Which of course would be undefined, as wd
has no storage allocated. 当然,哪一个是不确定的,因为
wd
没有分配存储空间。
This may account also for 3 ("no virtual base classes"), but since I pretty much never use virtual base classes, I'll defer to someone more familiar with them. 这可能也占了3个(“没有虚拟基类”),但是由于我几乎从不使用虚拟基类,因此我会请更熟悉它们的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.