Search code examples
c++c++11constructorstandardssemantics

Are they equivalent between implicit ctor, no-parameter-empty-body ctor and explicit default ctor?


struct A1
{
    int n;        
};

struct A2
{
    int n;
    A2(){}        
};

struct A3
{
    int n;
    A3() = default;        
};

Question 1:

Does the C++ standard guarantee the classes A1, A2, A3 are completely equivalent to each other?

Question 2:

A1 a1;
A2 a2;
A3 a3;

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard?


Solution

  • There's one difference that A1 and A3 are aggregate type, while A2 is not, because it has a user-defined constructor.

    class type (typically, struct or union), that has

    • ...
    • no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
    • ...

    It means for A1 and A3 they could be aggregate initialized, while A2 can't.

    A1 a1{99}; // fine;  n is initialized to 99
    A3 a3{99}; // fine;  n is initialized to 99
    A2 a2{99}; // error; no matching constructor taking int found
    

    Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard?

    According to the rule of default initialization, if they're of automatic storage duration, no zero-initialization here, all values will be indeterminate. On the other hand, static and thread-local objects get zero initialized.