gpt4 book ai didi

c++ - 我可以列出初始化只 move 类型的 vector 吗?

转载 作者:IT老高 更新时间:2023-10-28 11:59:07 26 4
gpt4 key购买 nike

如果我通过我的 GCC 4.7 快照传递以下代码,它会尝试将 unique_ptrs 复制到 vector 中。

#include <vector>
#include <memory>

int main() {
using move_only = std::unique_ptr<int>;
std::vector<move_only> v { move_only(), move_only(), move_only() };
}

显然这不起作用,因为 std::unique_ptr 不可复制:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete; std::unique_ptr<_Tp, _Dp> = std::unique_ptr]'

GCC 在尝试从初始化列表中复制指针时是否正确?

最佳答案

编辑:由于@Johannes 似乎不想发布最佳解决方案作为答案,所以我就这么做了。

#include <iterator>
#include <vector>
#include <memory>

int main(){
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))};
}

std::make_move_iterator 返回的迭代器取消引用时将 move 指向的元素。


原答案:我们将在这里使用一个小助手类型:

#include <utility>
#include <type_traits>

template<class T>
struct rref_wrapper
{ // CAUTION - very volatile, use with care
explicit rref_wrapper(T&& v)
: _val(std::move(v)) {}

explicit operator T() const{
return T{ std::move(_val) };
}

private:
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));
}

// lvalue reference can go away
template<class T>
void rref(T&) = delete;

很遗憾,这里的直接代码不起作用:

std::vector<move_only> v{ rref(move_only()), rref(move_only()), rref(move_only()) };

由于标准,无论出于何种原因,都没有像这样定义转换复制构造函数:

// in class initializer_list
template<class U>
initializer_list(initializer_list<U> const& other);

initializer_list<rref_wrapper<move_only>>由大括号初始化列表 ( {...} ) 创建的不会转换为 initializer_list<move_only>那个vector<move_only>需要。所以我们这里需要两步初始化:

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());

关于c++ - 我可以列出初始化只 move 类型的 vector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8468774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com