如何填充unique_ptr的数组? [英] How to fill an array of 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));
否,但这就是
所以,大概是这样的: 我还没有尝试过,也不知道是否需要摆弄它,以避免由于不可复制性引起的问题.希望移动语义就足够了. (当然,在C ++ 11中,您将需要您自己的 顺便说一句,您的 Is it possible to use For example:
No, but this is what Instead of being given a single value that's copied throughout the target range, So, probably, something like this: 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 By the way, your 这篇关于如何填充unique_ptr的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!std::unique_ptr<int> ar[3];
std::generate(
std::begin(ar),
std::end(ar),
[]() { return std::make_unique<int>(1); }
);
make_unique
函数.)>
.begin()
和.end()
是错误的(数组没有成员函数),因此(感谢Songyuanyao的提醒),我已纠正了这些问题.std:fill
to fill an array of unique_ptr
s? The intention is to have distinct pointers to distinct objects which are initialized with the same parameters.std::unique_ptr<int> ar[3];
std::fill(ar.begin(), ar.end(), make_unique_for_each_element_somehow<int>(1));
std::generate
is for.std::generate
is given a "generator" function that creates each value as needed.std::unique_ptr<int> ar[3];
std::generate(
std::begin(ar),
std::end(ar),
[]() { return std::make_unique<int>(1); }
);
make_unique
function.).begin()
and .end()
were wrong (arrays don't have member functions), so (thanks to a reminder from songyuanyao) I have corrected those.