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

struct A1
{
    int n;        
};

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

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

Question 1:

Does the standard C ++ classes A1, A2, A3is completely equivalent to each other?

Question 2:

A1 a1;
A2 a2;
A3 a3;

Not whether the compiler zero-initialized a1.n, a2.n, a3.nin accordance with the standard C ++?

+4
source share
2 answers

There is one difference: A1and A3 the aggregate type , and A2not, as it has a user -defined constructor.

the type of class (usually struct or union) that has

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

, A1 A3 , A2 .

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

a1.n, a2.n, a3.n ++?

, , , . , - zero initialized.

+2

, : , -

- ( 9) (12.1), (9.2), ( 11), ( 10) (10.3).

: POD / ?

, A1 A3, A2

struct A1
{
    int n;        
};

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

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


int main()
{
   A1 obj1{42};
   //A2 obj2{42}; // error
   A3 obj3{42};


   return 0;
}

A1 a1;    A2a2;    A3 a3;

a1.n, a2.n, a3.n ++

.

+2

Source: https://habr.com/ru/post/1661801/


All Articles