Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate Initialization - Vectors and Arrays

Tags:

c++

c++11

I know the following statements work

std::vector<int> a{1,2,4} --->A (Aggregate Initialization)

or the following statement(s)

std::vector<int> a;
a = {1,2,4};                ---->B  Variable already initialized. - Then aggregate initialization is called

However in case of Arrays

 int c[3]={1,4};  ---->C (1,4,0)

However the following is not allowed

int c[3]; 
c = {1,4};   ---->D

Now my question is why does B work and D doesnt ?

like image 242
Rajeshwar Avatar asked Sep 04 '25 04:09

Rajeshwar


1 Answers

std::vector<int> a{1,2,4};

This is initializer-list initialization, not aggregate, because vector is not an aggregate — its data is stored on the heap. You need to have #include <initializer_list> for it to work, although that header is typically included from <vector>.

a = {1,2,4};

This also goes through a function overloaded on std::initializer_list, and the semantics are the same as the function call:

a.assign( {1,2,4} );
 int c[3]={1,4};

This is aggregate initialization. However you cannot do c = { 3, 5, 6 } afterward, because the braced-init-lists may only be initializers for new variables, not operands to built-in expressions. (In a declaration, the = sign is just a notation for initialization. It is not the usual operator. Braced lists are specifically allowed by the grammar for assignment operators, but this usage is only valid with function overloading, which causes the list to initialize a new variable: the function parameter.)

The answer to your final question is that there's no way to write the necessary operator = overload for "naked" arrays, because it must be a member function. The workaround is to use std::copy and a std::initializer_list object.

like image 78
Potatoswatter Avatar answered Sep 05 '25 22:09

Potatoswatter