Home > Backend Development > C++ > How to Initialize a Vector with Move-Only Types in C ?

How to Initialize a Vector with Move-Only Types in C ?

Patricia Arquette
Release: 2024-12-23 21:31:11
Original
991 people have browsed it

How to Initialize a Vector with Move-Only Types in C  ?

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

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

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!

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