[英]moving into unique_ptr container
I have something I want to do that is extremely similar to the code snippet at cppreference.com for unique_ptr. 我要执行的操作与cppreference.com上的unique_ptr的代码段极为相似。 The snippet is produced below.
摘录如下。 It compiles fine.
它编译良好。
#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <iterator>
int main()
{
std::list<std::string> s{"one", "two", "three"};
std::vector<std::string> v1(s.begin(), s.end()); // copy
std::vector<std::string> v2(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end())); // move
std::cout << "v1 now holds: ";
for (auto str : v1)
std::cout << "\"" << str << "\" ";
std::cout << "\nv2 now holds: ";
for (auto str : v2)
std::cout << "\"" << str << "\" ";
std::cout << "\noriginal list now holds: ";
for (auto str : s)
std::cout << "\"" << str << "\" ";
std::cout << '\n';
}
What I really want is move the strings from s into a vector of unique_ptr . 我真正想要的是将字符串从s移到unique_ptr的向量中 。
so something like std::vector<std::unique_ptr<std::string>> v2(&std::make_move_iterator(s.begin()), &std::make_move_iterator(s.end()));
所以像
std::vector<std::unique_ptr<std::string>> v2(&std::make_move_iterator(s.begin()), &std::make_move_iterator(s.end()));
but this of course does not work. 但这当然行不通。
I can only get it to do what I want with this bit of code: 我只能用这段代码来做我想做的事情:
int main()
{
std::list<std::string> s{"one", "two", "three"};
std::vector<std::string> v1(s.begin(), s.end()); // copy
std::vector<std::unique_ptr<std::string>> v2;
for(auto& o : s)
{
std::unique_ptr<std::string> p ( new std::string(move(o)));
v2.push_back(move(p));
}
std::cout << "\nv2 now holds: ";
for (auto& pstr : v2)
std::cout << "\"" << *pstr << "\" ";
std::cout << "\noriginal list now holds: ";
for (auto str : s)
std::cout << "\"" << str << "\" ";
std::cout << '\n';
}
Is there a way to move resources into a container of unique_ptrs in one line? 有没有一种方法可以将资源移动到一行中的unique_ptrs容器中?
Yes if you use a make_unique
function as Herb Sutter recommends you can do: 是的,如果您按照Herb Sutter的建议使用
make_unique
函数,则可以执行以下操作:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T> ( new T( std::forward<Args>(args)... ) );
}
int main()
{
std::list<std::string> s{"one", "two", "three"};
std::vector<std::unique_ptr<std::string>> v2;
std::transform(begin(s), end(s), std::back_inserter(v2),
&make_unique<std::string, std::string&>
);
}
I have lifted make_unique
from Herbs page on the matter, it is included with C++14 or just use this version. 我已经从Herbs页面上取消了
make_unique
,它已包含在C ++ 14中或仅使用此版本。
http://herbsutter.com/gotw/_102/ http://herbsutter.com/gotw/_102/
Unfortunately we can't use type deduction so we have to provide the types manually. 不幸的是,我们不能使用类型推导,因此我们必须手动提供类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.