initializer_list-Initialization of Vectors with Move-Only Types
In C , when attempting to list-initialize a vector with elements of a move-only type, such as std::unique_ptr, the compiler may incorrectly try to copy the elements instead of moving them. This issue can be addressed using various techniques:
Intermediate Wrapper
To avoid copies, a wrapper type can be used to hold the move-only values as references. The rref_wrapper class demonstrates this approach by wrapping the move-only values and providing an operator to extract the underlying value. This allows the values to be moved into the vector without copying.
Example:
std::initializer_list<rref_wrapper<std::unique_ptr<int>>> il{ rref(std::make_unique<int>()), rref(std::make_unique<int>()), rref(std::make_unique<int>()) }; std::vector<std::unique_ptr<int>> v(il.begin(), il.end());
std::make_move_iterator
Another method involves using std::make_move_iterator to create iterators that, when dereferenced, move the pointed-to elements. This eliminates the need for a wrapper class.
Example:
std::unique_ptr<int> init[] = { std::make_unique<int>(), std::make_unique<int>(), std::make_unique<int>() }; std::vector<std::unique_ptr<int>> v{ std::make_move_iterator(std::begin(init)), std::make_move_iterator(std::end(init)) };
By employing these techniques, it becomes possible to list-initialize vectors with move-only types, ensuring efficient and correct ownership transfer.
The above is the detailed content of How to Correctly List-Initialize Vectors with Move-Only Types in C ?. For more information, please follow other related articles on the PHP Chinese website!