Home > Backend Development > C++ > How to Correctly List-Initialize Vectors with Move-Only Types in C ?

How to Correctly List-Initialize Vectors with Move-Only Types in C ?

Barbara Streisand
Release: 2025-01-01 07:20:10
Original
690 people have browsed it

How to Correctly List-Initialize Vectors with Move-Only Types in C  ?

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());
Copy after login

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))
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template