Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

c++14

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, … );
like image 903
yadhu Avatar asked Mar 10 '20 09:03

yadhu


People also ask

Should my constructors use initialization lists or assignment?

Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list.

Does initializer list call copy constructor?

And if we use Initializer List there are only two function calls: copy constructor + destructor call.

When should a constructor use an initializer?

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.


1 Answers

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.

like image 58
Valerii Boldakov Avatar answered Sep 28 '22 20:09

Valerii Boldakov