What is the basic structure of std :: initializer_list?

First part:

std::initializer_list is a really useful C ++ 11 function, so I wondered how it is implemented in the standard library. From what I read here , the compiler creates an array of type T and gives a pointer to initializer_list<T> .

It also states that copying initializer_list will create a new object that references the same data: why is this so? I would guess that this is either:

  • copies data for new initializer_list
  • transfers ownership of data to a new initializer_list

The second part of:

From one of the many online links for std::vector constructors:

 vector (initializer_list<value_type> il, const allocator_type& alloc = allocator_type()); 

(6) initializer list constructor

Creates a container with a copy of each of the elements in il in the same order.

I don't like move semantics yet, but il data can't be transferred to vector ? I don't know about the deep implementation of std::vector , but IIRC uses plain old arrays.

+6
source share
1 answer

What is the main structure of std::initializer_list ?

Most likely, just a pair of pointers, a pointer and a size. Clause 18.9 / 2 of C ++ 11 Standard even mentions this in a (non-normative) note:

An object of type initializer_list<E> provides access to an array of objects of type const E [Note: A pair of pointers or a pointer plus length will be obvious representations for initializer_list . initializer_list used to implement initializer lists, as specified in 8.5.4. Copy initializer list do not copy base elements. -end note]

Wherein:

I don’t like the semantics of movement yet, but is it possible to transfer il data to a vector?

No , you cannot move from the initializer_list elements, since the elements from the initializer_list must be immutable (see the first sentence of the paragraph above). This is also the reason why only const -qualified member functions give you access to elements.

+12
source

Source: https://habr.com/ru/post/946391/


All Articles