c++ - 有没有比这更简洁的方法来初始化 unique_ptr<char[]> ?

标签 c++ initialization c++14 smart-pointers unique-ptr

所以目前我有:

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::stringstd::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/

相关文章:

C++ : use of deleted function

c++ - 保持数据迭代器的 vector

c++ - mvrnorm 和 riwish

ios - 我正在用 Objective C 创建一个框架,它需要一个好的构造函数模式

c++ - 为引用元组赋值

c++ - 基指针中的派生对象如何调用基函数?

c++ - char* 和 int* 的区别

c++ - 使用带有虚函数的类的构造函数进行大括号初始化

c++ - C++ lambdas 是真正的闭包吗?通过引用捕获

c++ - const_forward 在 C++ 的可选实现中做了什么?