问题描述
我正在阅读这个http://en.wikipedia.org/wiki/C%2B%2B0x#Modification_to_the_definition_of_plain_old_data
它提到了平凡的默认构造函数、平凡的复制构造函数、复制赋值运算符、平凡的析构函数.什么是平凡和不平凡?
It mentions trivial default constructor, trivial copy constructor, copy assignment operator, trivial destructor. What is trivial and not trivial?
推荐答案
简单来说,平凡"的特殊成员函数的字面意思是一个以非常直接的方式完成其工作的成员函数.直截了当"对于不同类型的特殊成员函数意味着不同的东西.
In simple words a "trivial" special member function literally means a member function that does its job in a very straightforward manner. The "straightforward manner" means different thing for different kinds of special member functions.
对于默认的构造函数和析构函数,微不足道"的字面意思是什么都不做".对于复制构造函数和复制赋值运算符,平凡"的字面意思是等同于简单的原始内存复制"(例如使用 memcpy
进行复制).
For a default constructor and destructor being "trivial" means literally "do nothing at all". For copy-constructor and copy-assignment operator, being "trivial" means literally "be equivalent to simple raw memory copying" (like copy with memcpy
).
如果你自己定义了一个构造函数,它被认为是非平凡的,即使它什么都不做,所以一个平凡的构造函数必须由编译器隐式定义.
If you define a constructor yourself, it is considered non-trivial, even if it doesn't do anything, so a trivial constructor must be implicitly defined by the compiler.
为了使特殊的成员函数满足上述要求,类必须具有非常简单的结构,在创建或销毁对象时不得要求任何隐藏的初始化,或在创建或销毁对象时进行任何隐藏的附加内部操作被复制.
In order for a special member function to satisfy the above requirements, the class must have a very simplistic structure, it must not require any hidden initializations when an object is being created or destroyed, or any hidden additional internal manipulations when it is being copied.
例如,如果类有虚函数,那么在创建这个类的对象时需要一些额外的隐藏初始化(初始化虚方法表等),所以这个类的构造函数不会是微不足道的.
For example, if class has virtual functions, it will require some extra hidden initializations when objects of this class are being created (initialize virtual method table and such), so the constructor for this class will not qualify as trivial.
再举一个例子,如果一个类有虚拟基类,那么这个类的每个对象都可能包含指向同一对象其他部分的隐藏指针.这样的自引用对象无法通过简单的原始内存复制例程(如 memcpy
)复制.需要额外的操作来正确地重新初始化副本中的隐藏指针.出于这个原因,此类的复制构造函数和复制赋值运算符将不符合微不足道的条件.
For another example, if a class has virtual base classes, then each object of this class might contain hidden pointers that point to other parts of the very same object. Such a self-referential object cannot be copied by a simple raw memory copy routine (like memcpy
). Extra manipulations will be necessary to properly re-initialize the hidden pointers in the copy. For this reason the copy constructor and copy-assignment operator for this class will not qualify as trivial.
出于显而易见的原因,此要求是递归的:类的所有子对象(基类和非静态成员)还必须具有普通构造函数.
For obvious reasons, this requirement is recursive: all subobjects of the class (bases and non-static members) must also have trivial constructors.
这篇关于什么是 C++ 中的非平凡构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!