使用这个:
https://stackoverflow.com/a/16968463/629530 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 给调用者以避免返回中的复制?或者我可以通过输出参数来完成此操作吗?
正如评论中指出的 - 可调用包含在std::function
必须复制可构造。因此,不要返回函数,只需返回 lambda 本身,如下所示:
auto get_func()
{
auto i = std::make_unique<int>(2);
return [i=std::move(i)]() {
return *i;
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)