我有一个函数,它使用move-capture构造一个lambda函数(仅限C++ 1y)并返回它.
#include <iostream>
#include <functional>
#include <memory>
using namespace std;
function<int ()> makeLambda(unique_ptr<int> ptr) {
return [ ptr( move(ptr) ) ] () {
return *ptr;
};
}
int main() {
// Works
{
unique_ptr<int> ptr( new int(10) );
auto function1 = [ ptr(move(ptr)) ] {
return *ptr;
};
}
// Does not work
{
unique_ptr<int> ptr( new int(10) );
auto function2 = makeLambda( std::move(ptr) );
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,似乎在返回时,unique_ptr<int>调用了复制构造函数.为什么这个/我怎么能绕过这个?
问题是std::function<int ()>返回类型,它试图制作lambda的副本.这将失败,因为复制构造函数由于存在而被隐式删除std::unique_ptr.不是将lambda存储在std::function对象中,而是使用返回类型推导,现在将移动lambda.
auto makeLambda(unique_ptr<int> ptr) {
return [ ptr( move(ptr) ) ] () {
return *ptr;
};
}
Run Code Online (Sandbox Code Playgroud)
您还应该更改makeLambdato 的参数类型unique_ptr<int>&&
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |