如何填充unique_ptr的数组? [英] How to fill an array of unique_ptr?

查看:329
本文介绍了如何填充unique_ptr的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用std:fill填充unique_ptr s的数组?目的是要有不同的指针指向不同的对象,这些对象使用相同的参数初始化.

例如:

std::unique_ptr<int> ar[3];
std::fill(ar.begin(), ar.end(), make_unique_for_each_element_somehow<int>(1));

解决方案

否,但这就是

所以,大概是这样的:

std::unique_ptr<int> ar[3];
std::generate(
   std::begin(ar),
   std::end(ar),
   []() { return std::make_unique<int>(1); }
);

我还没有尝试过,也不知道是否需要摆弄它,以避免由于不可复制性引起的问题.希望移动语义就足够了.

(当然,在C ++ 11中,您将需要您自己的make_unique函数.)

顺便说一句,您的.begin().end()是错误的(数组没有成员函数),因此(感谢Songyuanyao的提醒),我已纠正了这些问题.

Is it possible to use std:fill to fill an array of unique_ptrs? The intention is to have distinct pointers to distinct objects which are initialized with the same parameters.

For example:

std::unique_ptr<int> ar[3];
std::fill(ar.begin(), ar.end(), make_unique_for_each_element_somehow<int>(1));

解决方案

No, but this is what std::generate is for.

Instead of being given a single value that's copied throughout the target range, std::generate is given a "generator" function that creates each value as needed.

So, probably, something like this:

std::unique_ptr<int> ar[3];
std::generate(
   std::begin(ar),
   std::end(ar),
   []() { return std::make_unique<int>(1); }
);

I haven't tried it, and don't know whether you need to fiddle with it at all in order to avoid problems stemming from non-copyability. Hopefully move semantics are enough.

(Of course, in C++11, you will need your own make_unique function.)

By the way, your .begin() and .end() were wrong (arrays don't have member functions), so (thanks to a reminder from songyuanyao) I have corrected those.

这篇关于如何填充unique_ptr的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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