创建不可移动类型的std :: vector [英] Creating std::vector of nonmovable type

查看:81
本文介绍了创建不可移动类型的std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: vector 名为 args (我不知道向量的大小编译时间)和非移动类型 NonMoveable

I have a std::vector named args (I don’t know the size of the vector at compile time) and a non movable type NonMoveable.

我想创建一个与args大小相同的向量,因此等于
{NonMovable(args [0],Additional_arg),NonMovable(args [1],Additional_arg),…,NonMovable(args.back(),Additional_arg)}

I want to create a vector of the same size as args, so that it equals to {NonMovable(args[0], additional_arg), NonMovable(args[1], additional_arg), …, NonMovable(args.back(), additional_arg)}

我以后不需要更改向量的大小。我该怎么做?

I don’t need to change the size of the vector later. How do I do that?

我不能 reserve()然后 emplace_back( ),因为 emplace_back()需要移动(以允许重新分配,这在我的情况下是不可能的)

I can’t reserve() then emplace_back() because emplace_back() requires moving (to allow reallocation which is not possible in my case)

我不想使用 std :: list ,因为它不连续。

I do not want to use std::list because it is not contiguous.

推荐答案

您可以:


  • 具有 vector< unique_ptr< T>> vector< optional< T>> vector< some_other_defer_storage_mechanism< T>< 而不只是 vector< T> -这些都是包装器类型,它们添加了一些功能 T 而不会影响 T unique_ptr< T> 使其可移动, optional< T> 确保默认构造,因此您可以使用正确的大小,然后在可选等内的 emplace()进行构造)

  • 使用 deque< T> emplace_back 的可移动性(尽管失去了连续性)

  • 编写自己的动态数组,其大致等效于 pair< unique_ptr< T [],size_t> 只是为 n T s,然后在每个位置上放置新闻,以确保销毁操作正确。实施起来并不是很糟糕-因为您不会更改大小,因此需要支持非常少量的整体操作。

  • Have a vector<unique_ptr<T>> or vector<optional<T>> or vector<some_other_defer_storage_mechanism<T>> instead of just vector<T> - these are all wrapper types that adding some functionality T without affecting T (unique_ptr<T> makes it movable, optional<T> ensures default construction so you can construct with the right size then emplace() within the optional, etc.)
  • Use deque<T> which does not require movability for emplace_back (although you lose Contiguity)
  • Write your own dynamic array that is roughly equivalent to a pair<unique_ptr<T[]>, size_t> that just allocates space for n Ts and then placement-news onto each of them, ensuring that destruction does the right thing. This isn't so bad to implement - since you won't be changing the size, you need to support a very minimal amount of overall operations.

其中哪一个是最佳答案,实际上取决于。

Whichever one of these is the best answer really depends.

这篇关于创建不可移动类型的std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆