Why isn't move construction used when initiating a vector from initializer list (via implicit constructor)

筅森魡賤 提交于 2019-12-03 14:43:23

I thought I had an initializer list of integers, but I'm now wondering if what I have in between is an initializer list of Cs, which can't be moved from (as its const). Is this a correct interpretation?

This is correct. vector<C> does not have an initializer_list<int> constructor or even an initializer_list<T> constructor for some template parameter T. What it does have is an initializer_list<C> constructor - which is built up from all the ints you pass in. Since the backing of initializer_list is a const array, you get a bunch of copies instead of a bunch of moves.

As detailed in my comment you get the copies because a vector of type std::vector<C> expects an std::initializer_list<C> so your list of int's is constructed into a temporary list of C's and it is that list of C's that is being copied from.

One way you could get around this though is to make a helper function. Using something like

template <typename T, typename Y>
std::vector<T> emplace_list(std::initializer_list<Y> list)
{
    std::vector<T> temp;
    temp.reserve(list.size());
    for (const auto& e: list)
        temp.emplace_back(e);
    return temp;
}

int main()
{
    auto vec2 = emplace_list<C>({1,2,3,4,5});
}

You can avoid making copies of the elements from the list because you directly construct them into the vector using emplace_back. If the compiler applies NRVO then you do not even have a move of the vector out of the function. See this live example for g++'s full output. Do note I have the constructor printing just so you can see it is the only one called.

Thinking a bit more. Here's the self answer:

std::vector<C> does not have a constructor of initializer_list<int>, or event of T convertible to C. It does have the constructor

vector( std::initializer_list<T> init,
    const Allocator& alloc = Allocator() );

So, the initializer_list argument list will be an initializer_list<C>. Said constructor can do nothing else than copy from the initializer list since they are immutable (used to say const, but the effect here is the same, it can't be move from).

Oh, and that's also what NathanOliver wrote in a comment as I wrote this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!