csguy
csguy

Reputation: 1474

Initialization of array type (C++)

According to https://en.cppreference.com/w/cpp/language/list_initialization, one of the effects of list initialization is:

If T is an aggregate type, aggregate initialization is performed.

Since arrays are aggregate types, when I initialize an array int array[3] = {1, 2};,

I believe what happens is

  1. List initialization
  2. Aggregate initialization
  3. Copy initialization where 1, 2 are copy initialized from the corresponding clause of the initializer list
  4. Remaining values are value initialized (zero initialization)

This makes sense to me as the values of the array will be {1, 2, 0}.

However, as I continued reading I noticed another effect of list initialization which was:

If T is an aggregate type and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).

So will declaring an array int array[3] = {1}; where the "initializer list has a single element" be a different process than when there is more than one element? (i.e. int array [3] = {1, 2};)? This doesn't make sense to me, but I'm not sure what I'm missing.

Upvotes: 1

Views: 81

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

That effect won't be applied, as the quotes said,

If T is an aggregate type and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).

Given int array[3] = {1};, {1} has a single element 1 of type int, which is not a same or derived type of the array type int[3].

Upvotes: 3

Related Questions