Initialization of Vector with Move-Only Type
G attempts to copy unique_ptr objects in vector initialization, which fails due to the copy-constructor being inaccessible. The error message correctly highlights the issue of attempting to copy non-copyable objects.
Utilizing Move Iterators
To resolve this issue, you can leverage move iterators, which move elements when dereferenced:
using move_only = std::unique_ptr<int>; move_only init[] = { move_only(), move_only(), move_only() }; std::vector<move_only> v{std::make_move_iterator(std::begin(init)), std::make_move_iterator(std::end(init))};
Employing a Helper Type
Alternatively, you can utilize a helper type to achieve move semantics in initialization:
template<class T> struct rref_wrapper { explicit rref_wrapper(T&& v) : _val(std::move(v)) {} explicit operator T() const { return T{std::move(_val)}; } T&& _val; }; // Only usable on temporaries template<class T> typename std::enable_if< !std::is_lvalue_reference<T>::value, rref_wrapper<T> >::type rref(T&& v) { return rref_wrapper<T>(std::move(v)); } std::initializer_list<rref_wrapper<move_only>> il{rref(move_only()), rref(move_only()), rref(move_only())}; std::vector<move_only> v(il.begin(), il.end());
The above is the detailed content of How to Initialize a Vector with Move-Only Types in C ?. For more information, please follow other related articles on the PHP Chinese website!