What is a non-trivial constructor in C++?(转载)

转自stackoverflow:http://stackoverflow.com/questions/3899223/what-is-a-non-trivial-constructor-in-c

Answer 1:

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.

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.

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.

Answer 2:

There are correct answers already, but here is the quote from the Standard (which I was looking for when I came across this post):

(§12.1/5)  A default constructor is trivial if it is not user-provided and if:

— its class has no virtual functions (10.3) and no virtual base classes (10.1), and

— no non-static data member of its class has a brace-or-equal-initializer, and — all the direct base classes of its class have trivial default constructors, and

— for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default constructor.

This is from C++11. C++03 lacks the second item and uses the phrase implicitly declared instead of not user-provided. It is otherwise identical.

Note that this specification only covers trivial default constructors. The word attribute trivial can also be used in different contexts, e.g. copy constructors.

posted on 2013-08-22 10:26  夜月升  阅读(758)  评论(0编辑  收藏  举报

导航