Why would the implicitly generated constructor (et al.) be more efficient than a user-defined (trivial) one?

前端 未结 4 1230
梦毁少年i
梦毁少年i 2020-12-20 13:04

I read this article from D. Kalev this morning about the new c++11 feature \"defaulted and deleted functions\", and can\'t understand the part about performance, namely:

4条回答
  •  旧巷少年郎
    2020-12-20 14:06

    It makes no sense whatsoever to talk about "manual definition of a special member function (even if it's trivial)", because user-provided special member functions are, by definition, non-trivial. This non-triviality comes into play when using type traits, and also POD-ness, and many optimizations are only possible with trivial or POD types.

    A better restatement of the same quote would be:

    The defaulted special member functions enable libraries to detect that calls to these functions may be omitted entirely.

    From section 12.1 [class.ctor]

    A default constructor is trivial if it is neither user-provided nor deleted 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.

    Otherwise, the default constructor is non-trivial.

    From section 12.8 [class.copy]:

    A copy/move constructor for class X is trivial if it is neither user-provided nor deleted and if

    • class X has no virtual functions (10.3) and no virtual base classes (10.1), and
    • the constructor selected to copy/move each direct base class subobject is trivial, and
    • for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

    otherwise the copy/move constructor is non-trivial.

    From section 9, [class]:

    A trivially copyable class is a class that:

    • has no non-trivial copy constructors (12.8),
    • has no non-trivial move constructors (12.8),
    • has no non-trivial copy assignment operators (13.5.3, 12.8),
    • has no non-trivial move assignment operators (13.5.3, 12.8), and
    • has a trivial destructor (12.4).

    A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable. [ Note: in particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes. — end note ]

提交回复
热议问题