use*_*792 4 c++ initialization smart-pointers unique-ptr c++14
所以目前我有:
std::string a;
std::unique_ptr<char[]> b(std::make_unique<char[]>(a.size() + 1));
std::copy(std::begin(a), std::end(a), b.get());
Run Code Online (Sandbox Code Playgroud)
是否可以一步直接初始化?
是否可以一步直接初始化?
我建议将其保留为std::stringor std::vector<char>。
但是,如果你真的坚持,是的!使用立即调用 lambda,可以做到这一点。
std::unique_ptr<char[]> b = [&a]() {
auto temp(std::make_unique<char[]>(a.size() + 1));
std::copy(std::begin(a), std::end(a), temp.get());
return temp;
}(); // invoke the lambda here!
Run Code Online (Sandbox Code Playgroud)
在temp将建设移动b。
(见演示)
如果a以后不使用该字符串,您可以将其移动到std::unique_ptr<char[]>, 使用std::make_move_iterator.
#include <iterator> // std::make_move_iterator
std::unique_ptr<char[]> b(std::make_unique<char[]>(a.size() + 1));
std::copy(std::make_move_iterator(std::begin(a)),
std::make_move_iterator(std::end(a)), b.get());
Run Code Online (Sandbox Code Playgroud)
如果这需要在一个步骤中进行,请像上面一样将其打包到 lambda 中。