yadhu
yadhu

Reputation: 1333

Why does the std::vector constructor accept initializer list by copy?

When I was trying to understand the different types of initialization in modern C++, I came across the initialization of std::vector<T> with an initialization list. To allow initialization with initializer list data structure such as std::vector<T> should have a constructor that accepts initializer as the parameter. I observed is that std::vector<T> accepts the initializer list by copy not as a reference, accepting by copy when we have a huge number of elements can be very expensive. Why is it so is there any particular reason why the initializer list for taking it as a copy instead of reference?

From https://en.cppreference.com/w/cpp/container/vector/vector

vector( std::initializer_list<T> init, … ); (9)     (since C++11)

Why not?

vector( std::initializer_list<T>& init, … );

Upvotes: 5

Views: 691

Answers (2)

Valerii Boldakov
Valerii Boldakov

Reputation: 1751

std::initializer_list doesn't copy underlying objects.

As you can read here:

Copying a std::initializer_list does not copy the underlying objects.

So it doesn't really waste a lot of memory or time.

Upvotes: 5

andreilomakin
andreilomakin

Reputation: 419

According to cppreference.com,

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T.

Initializer lists may be implemented as a pair of pointers or pointer and length. Copying a std::initializer_list does not copy the underlying objects.

So, despite the fact that the std::initializer_list creates a temporary array, the elements of this array are not copied even if the std::initializer_list is passed by value. But if you like, you can accept objects of this type by a constant reference. This works great in my projects. For example:

auto some_function(const std::initializer_list<T>& list);

Upvotes: 3

Related Questions