mardi 10 mars 2020

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, … );

Aucun commentaire:

Enregistrer un commentaire