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, … );
Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list.
And if we use Initializer List there are only two function calls: copy constructor + destructor call.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With