所以目前我有:
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());
是否可以一步直接初始化?
最佳答案
Is it is possible to initialize this directly in one step?
我建议将其保留为
std::string
或 std::vector<char>
.但是,如果你真的坚持,是 !使用 immediately invoking a 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!
temp
将搬迁至 b
.( See a Demo )
如果字符串
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());
如果这需要在一个步骤中进行,请像上面一样将其打包到 lambda 中。
关于c++ - 有没有比这更简洁的方法来初始化 unique_ptr<char[]> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63339179/