Do I need to std::move an std::initializer_list?

238 Views Asked by At

I want to pass a list-initialized vector to a worker function through a wrapper. I don't need the values in the original function (main), so should I move it?

The doc states that:

copying a std::initializer_list does not copy the underlying objects.

So costs are probably minimal, but is there still an advantage to moving it or is the list copy-elided and the vector directly list-initialized?

(Compiling) Code:

#include <iostream>
#include <vector>


void worker(std::vector<int>&& some_ints)
{
    std::cout << "I hope my ints arrive here without further overhead :)" << std::endl;
}

void wrapper(std::vector<int>&& some_ints)
{
    worker(std::move(some_ints));
}

int main()
{
    wrapper( { 1, 5 } ); // <-- std::move here?
}
1

There are 1 best solutions below

1
dfrib On

A braced-init-list is not a std:initializer_list.

Here:

wrapper( { 1, 5 } );

overload resolution finds the void wrapper(std::vector<int>&&) overload which is a viable overload for the call: creating a temporary std::vector<int> object (by list-initialization via the std::initializer_list<T> constructor of std::vector<T>) which binds to the rvalue reference parameter of the wrapper function.

Trying to move a braced-init-list

wrapper(std::move({ 1, 5 }));  // error

is illegal (T in the std::move<T>(T&&) function template cannot be deduced).