【发布时间】:2014-06-23 22:06:18
【问题描述】:
我有一个函数,它使用移动捕获(仅限 C++1y)构造一个 lambda 函数并返回它。
#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;
}
然而,似乎在返回时,unique_ptr<int> 的复制构造函数被调用了。为什么会这样/我该如何解决?
【问题讨论】:
-
如果将
auto function1 = ...更改为function<int()> function1 = ...会发生什么。我认为问题在于使用std::function,而不是使用返回类型。 -
嗯,它有所作为。如果我进行更改,第一部分将不再有效。
-
哦,对不起。我误解了你的评论。
-
顺便说一句,你的代码很吵。在现代 C++ 中,我可能更愿意写成 like this。