gpt4 book ai didi

c++ - 有没有比这更简洁的方法来初始化 unique_ptr

转载 作者:行者123 更新时间:2023-12-01 14:04:16 25 4
gpt4 key购买 nike

所以目前我有:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com