pingul
pingul

Reputation: 3473

Is an empty constructor with initializer list considered trivial?

Is the following constructor considered trivial?

struct A
{
    A() : a(nullptr) {}
private:
    int* a;
};

These examples makes me a little confused. With c++11 this should also be possible:

struct A
{
private:
    int* a{nullptr};
};

and a should be properly initialized to nullptr. Here I did not define the constructor, but it should have the same form as the first implementation. Is either of these classes considered trivial?

The purpose of me asking is if I can expect move/copy constructors and assignment operators being automatically generated.

Upvotes: 3

Views: 529

Answers (1)

AlexD
AlexD

Reputation: 32576

Is the following constructor considered trivial?

A() : a(nullptr) {}

No, because it is user-defined.

struct A
{
private:
    int* a{nullptr};
};

No, because it has brace initializer for a non-static member.

According to the standard (emphasis mine):

12.1 Constructors
....

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.40).
....

A default constructor is trivial if it is not user-provided and if:
....
no non-static data member of its class has a brace-or-equal-initializer, and
....

Otherwise, the default constructor is non-trivial.


The purpose of me asking is if I can expect move/copy constructors and assignment operators being automatically generated.

As @M.M and @NicolBolas commented, generation of these constructors and operators are not impacted by existence of the trivial constructor.

The rules are a bit complicated and not very consistent.

The copy constructor is generated only if there is no explicitly declared one. (And it is deleted if the move constructor or the move assignment operator is declared.)

Similarly, the copy assignment operator is generated only if there is no explicitly declared one. (And again, it is deleted if the move constructor or the move assignment operator is declared.)

The move constructor is generated only if there are no explicitly declared move constructor, move operator, copy constructor, copy assignment and destructor.

The same rule is for the move assignment operator.

Upvotes: 8

Related Questions