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

前端 未结 5 1153
感情败类
感情败类 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:39

    As it has been pointed out, it is not possible to initialize a vector of move-only type with an initializer list. The solution originally proposed by @Johannes works fine, but I have another idea... What if we don't create a temporary array and then move elements from there into the vector, but use placement new to initialize this array already in place of the vector's memory block?

    Here's my function to initialize a vector of unique_ptr's using an argument pack:

    #include 
    #include 
    #include   /// @see http://stackoverflow.com/questions/7038357/make-unique-and-perfect-forwarding
    
    template 
    inline std::vector> make_vector_of_unique(Items&&... items) {
        typedef std::unique_ptr value_type;
    
        // Allocate memory for all items
        std::vector result(sizeof...(Items));
    
        // Initialize the array in place of allocated memory
        new (result.data()) value_type[sizeof...(Items)] {
            make_unique::type>(std::forward(items))...
        };
        return result;
    }
    
    int main(int, char**)
    {
        auto testVector = make_vector_of_unique(1,2,3);
        for (auto const &item : testVector) {
            std::cout << *item << std::endl;
        }
    }
    

提交回复
热议问题