DoehJohn
DoehJohn

Reputation: 233

Different ways of initializing an object with default constructor in C++

struct A 
{
 int a;
 std::string str;
};

A a;// 1
A a{};// 2
A a = {};// 3
A a = A();// 4

There seems to be all options. In case 1 and 4 a will be uninitialized, in 2 and 3 a will be initialized with zero and they both are same and just the matter of style or there is some difference? 4 supposed to first create a temporary object and then assign it to an a, but it will happen only if I will turn off comliler's optimization completely, right?

Upvotes: 2

Views: 1162

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

For all the cases the data member str is always default-initialized by the default constructor of std::string. Due to the different initialization styles, the data member a might be initialized to 0 or indeterminate value. In details,

  1. The 1st one is default initialization, as the result a.a is initialized to indeterminate value (or gets zero-initialized to 0 if a is static or thread-local object), a.str is initialized by its default constructor.

  2. The 2nd one is direct-list-initialization and aggregate initialization is performed, as the result a.a is value-initialized (zero-initialized) to 0, a.str is initialized by its default constructor.

  3. The 3rd one is copy-list-initialization and aggregate initialization is performed, as the result a.a is value-initialized (zero-initialized) to 0, a.str is initialized by its default constructor.

  4. In concept the 4th one is copy initialization, a is copy-initialized from A() (value-initialized temporary A). Because of copy elision (since C++17 it's mandatory) a might be value-initialized directly, as the result (which doesn't get changed by copy elision) a.a is zero-initialized to 0, a.str is initialized by its default constructor.

Upvotes: 4

Related Questions