Can I list-initialize a vector of move-only type?

前端 未结 5 1158
感情败类
感情败类 2020-11-22 08:30

If I pass the following code through my GCC 4.7 snapshot, it tries to copy the unique_ptrs into the vector.

#include 
#include <         


        
5条回答
  •  天命终不由人
    2020-11-22 08:51

    As mentioned in other answers, the behaviour of std::initializer_list is to hold objects by value and not allow moving out, so this is not possible. Here is one possible workaround, using a function call where the initializers are given as variadic arguments:

    #include 
    #include 
    
    struct Foo
    {
        std::unique_ptr u;
        int x;
        Foo(int x = 0): x(x) {}
    };
    
    template        // recursion-ender
    void multi_emplace(std::vector &vec) {}
    
    template
    void multi_emplace(std::vector &vec, T1&& t1, Types&&... args)
    {
        vec.emplace_back( std::move(t1) );
        multi_emplace(vec, args...);
    }
    
    int main()
    {
        std::vector foos;
        multi_emplace(foos, 1, 2, 3, 4, 5);
        multi_emplace(foos, Foo{}, Foo{});
    }
    

    Unfortunately multi_emplace(foos, {}); fails as it cannot deduce the type for {}, so for objects to be default-constructed you have to repeat the class name. (or use vector::resize)

提交回复
热议问题