gpt4 book ai didi

c++ - 如何返回带有捕获的 unique_ptr 的 lambda

转载 作者:行者123 更新时间:2023-11-30 04:43:14 25 4
gpt4 key购买 nike

<分区>

使用这个:

https://stackoverflow.com/a/16968463/629530

我可以在 lambda 中捕获一个 unique_ptr。但是当我尝试使用捕获的 unique_ptr 传递 lambda 函数时遇到问题。这是一个例子:

// test.cc
#include <iostream>
#include <memory>

std::function<int()>
get_func()
{
auto i = std::make_unique<int>(2);
return [i=std::move(i)]() {
return *i;
};
}

int
main(int argc, char* argv[])
{
auto func = get_func();
std::cout << "val: " << func() << std::endl;
return 0;
}

当我编译时(在我的 mac 上运行,但我在 Linux 中看到类似的错误):

g++ -g -Wall -Werror -std=c++17 test.cc -o test

有很多输出,但这似乎是最重要的部分:

test.cc:9:13: note: copy constructor of '' is implicitly deleted because field '' has a deleted copy constructor
return [i=std::move(i)]() {
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/memory:2490:3: note: copy constructor is implicitly deleted because 'unique_ptr<int, std::__1::default_delete<int> >' has a user-declared move constructor
unique_ptr(unique_ptr&& __u) noexcept

如果我理解正确的话,发生这种情况是因为正在复制函数本身。有没有办法让我 std::move 函数到调用者以避免返回中的拷贝?或者我可以使用输出参数完成此操作吗?

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