In this code
vector<std::string> vec = { "long string", "exterminate" };
an initializer_list of std::string is created and each element in copied into vec. This is inefficient and makes it impossible to initialize vectors with move only types. Why can't the constructor perfectly forward the arguments?
If that was true you could do this:
vector<unique_ptr<int>> vec = {
make_unique<int>(5), make_unique<int>(55), make_unique<int>(-4)
};
Instead of this:
vector<unique_ptr<int>> vec;
vec.push_back(make_unique<int>(5));
vec.push_back(make_unique<int>(55));
vec.push_back(make_unique<int>(-4));
Furthermore, if vector cares about copying elements in its constructor, why are you allowed to move elements with push_back?
Unfortunately, the behaviour which you want to obtain is impossible using
std::vectorconstructor. It can not use variadic template, becausestd::vectoris a container of single type, so variadic template constructor would not be type-safe. If you really want to constructstd::vectorcontainer with non-copyable elements, consider using the following function:You need to pass
std::arrayto it in this way:You can simply
push_backnon-copyable types, because they are notconst, while they areconstinstd::initializer_list. For this reason, the function above is usingstd::arrayfor this purpose, because this container allows access to its elements by non-constant reference or iterator, which allows non-constant access.