我曾尝试以下:如何将unique_ptr捕获到lambda表达式中?
std::function<void()> getAction(std::unique_ptr<MyClass> &&psomething){
//The caller given ownership of psomething
return [psomething](){
psomething->do_some_thing();
//psomething is expected to be released after this point
};
}
不过,这并不编译。有任何想法吗?
UPDATE:
的建议,一些新的语法需要明确指定,我们需要将所有权转移给拉姆达,我现在想的语法如下:
std::function<void()> getAction(std::unique_ptr<MyClass> psomething){
//The caller given ownership of psomething
return [auto psomething=move(psomething)](){
psomething->do_some_thing();
//psomething is expected to be released after this point
};
}
难道是一个好的候选人?
更新1:
我会告诉我的执行move
和copy
如下:
template<typename T>
T copy(const T &t) {
return t;
}
//process lvalue references
template<typename T>
T move(T &t) {
return std::move(t);
}
class A{/*...*/};
void test(A &&a);
int main(int, char **){
A a;
test(copy(a)); //OK, copied
test(move(a)); //OK, moved
test(A()); //OK, temporary object
test(copy(A())); //OK, copying temporary object
//You can disable this behavior by letting copy accepts T &
//test(move(A())); You should never move a temporary object
//It is not good to have a rvalue version of move.
//test(a); forbidden, you have to say weather you want to copy or move
//from a lvalue reference.
}
这是理想的解决方案。 –
在这种情况下,何时发布唯一指针?当lambda呢? – Leo
@Leo必须将唯一指针移动到lambda的数据块(lambda是带有(())运算符的对象),然后在释放lambda对象后释放。如果lambda对象没有移动,则可以在'go.run'之后释放作为右值的lambda对象。如果它被移动,它可以在任何时候被释放,如果你想安排'do_something_with'稍后运行,这是有意义的。 –