2
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?

1
  • 1
    In case 4 a and a.a are both initialized Commented Jun 15, 2020 at 1:41

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

a's default constructor is not called in cases 2,3 which are aggregate initialization
@M.M I don't consider that because I think A is non an aggregate bcecause it has a non-aggregate member str, it seems wrong...
The meaning of "aggregate" is defined by [dcl.init.aggr], there is no prohibition of subobjects being non-aggregate
@M.M Thanks for pointing that, my misunderstanding.
@M.M what do you mean that "default constructor is not called"? In this case, where default constructor is added by compiler? As when I added to the class default constructor it is called in all cases.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.