Unbound POD Element Initialization Elements

This code:

struct Test {
    int a = 1;
    int b = 2;
};

Test test1;
Test test2{};

As test2I'm sure test2.a == 1, and test2.b == 2. Is it guaranteed (or not) for test1(without {})?

+6
source share
3 answers

Line

Test test1;

equivalent to initialization with a standard constructor, which in the absence of a handwritten one with an explicit initialization list and without Test() = deleted;will ultimately set two members to their given initial values 1and 2.

The "default constructor" is a constructor that can be called without arguments, which exactly matches the above statement.

- 12.1 4:

X X, ...

5:

, , , (3.2), (1.8)...

+7

, .

,

T - , . ( ) ;

, ; , .

, ,

and bases (since C++17) , and bases (since C++17) by their default initializers, if provided in the class definition, and otherwise (since C++14)...

, .

+6

test1 , a 1, b 2.

++ 11 FAQ, :

++ 11 , , ( ). , . :

class A {
  public:
    int a = 7;
};

:

class A {
  public:
    int a;
    A() : a(7) {}
};
+4

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


All Articles