Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can an initializer list only be used on declaration?

Arrays can be initialized with what's called an initialization list.

Eg:

int my_array[3] = {10, 20, 30};

That's very useful when we have a set of initial values for our array. However this approach doesn't work to assign new values to the array once it's declared.

my_array = {10, 20, 30};

error: assigning to an array from an initializer list

However sometimes we have processes where we need to initialize our arrays several times to some initial values (eg: inside a loop) so I think it would be very useful to be able to use initializer lists to assign values to variables already declared.

My question is: Is there a reason for having such a feature at declaration time but not once the array is declared? Why does it work in one case but not in the other case?

like image 251
Sembei Norimaki Avatar asked May 09 '19 09:05

Sembei Norimaki


People also ask

What is the purpose of initializer list?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

What are the advantages of initializer list?

The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.

What is the name of the initializer in a class declaration?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type.

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.


2 Answers

Arrays are second-class citizens in C++. They are objects, but they are severely restricted: they can't be copied, they are decayed into pointers in various contexts, etc. Consider using std::array, which is a (fixed-size) wrapper on top of builtin arrays, but is a first-class citizen which supports various convenience features:

std::array<int, 3> my_array = {10, 20, 30};
my_array = {40, 50, 60};

This works because, per [array.overview]/2,

std::array is an aggregate type that can be list-initialized with up to N elements whose types are convertible to T.

live demo

This also works with std::vector. Vectors are a different story, so I am not going to go into details here.


If you prefer to insist on builtin arrays, here's a workaround I designed to enable assigning a list of values to a builtin array (respecting value categories), using template metaprogramming techniques. A compile-time error is (correctly) raised if the length of the array and the value list mismatch. (Thanks to Caleth's comment for pointing this out!) Note that copying builtin arrays is impossible in C++; that's why we have to pass the array to the function.

namespace detail {
  template <typename T, std::size_t N, std::size_t... Ints, typename... Args>
  void assign_helper(T (&arr)[N], std::index_sequence<Ints...>, Args&&... args)
  {
    ((arr[Ints] = args), ...);
  }
}

template <typename T, std::size_t N, typename... Args>
void assign(T (&arr)[N], Args&&... args)
{
  return detail::assign_helper(arr, std::make_index_sequence<N>{}, std::forward<Args>(args)...);
}

And to use it:

int arr[3] = {10, 20, 30};
assign(arr, 40, 50, 60);

Now arr consists of 40, 50, 60.

live demo

like image 186
L. F. Avatar answered Oct 04 '22 05:10

L. F.


Is there a reason for having such a feature at declaration time but not once the array is declared? Why does it work in one case but not in the other case?

The x = {a, b, ...} syntax involves a specific type of initializer lists called copy-list-initialization. The cppreference mentions the possible ways to use copy-list initialization:

  • T object = {arg1, arg2, ...}; (6)
  • function( { arg1, arg2, ... } ) (7)
  • return { arg1, arg2, ... } ; (8)
  • object[ { arg1, arg2, ... } ] (9)
  • object = { arg1, arg2, ... } (10)
  • U( { arg1, arg2, ... } ) (11)
  • Class { T member = { arg1, arg2, ... }; }; (12)

The array syntax that you tried T myArr[] = {a, b, c...} works and is numerated as (6) initialization of a named variable with a braced-init-list after an equals sign.

The syntax that doesn't work for you (myArr = {a, b, ...}) is numerated as (10) and it's called list-initialization in an assignment expression. The thing about assignment expressions is that the left side must be a so-called lvalue, and although arrays are lvalues, they cannot appear on the left side of assignments as per the specification.


That being said, it wouldn't be very hard to work around assignment by copying an initializer list onto the array as such:

#include <algorithm>
#include <iostream>

int main() {
  int arr[] = {1, 2, 3};

  auto itr = arr;
  auto assign = {5, 2, 1};
  std::copy(assign.begin(), assign.end(), itr);
}
like image 21
Filip Dimitrovski Avatar answered Oct 04 '22 06:10

Filip Dimitrovski