gpt4 book ai didi

c++ - 如何将 unique_ptr 捕获到 lambda 表达式中?

转载 作者:IT老高 更新时间:2023-10-28 12:31:32 37 4
gpt4 key购买 nike

我尝试了以下方法:

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
};
}

但它不能编译。有什么想法吗?

更新:

正如建议的那样,需要一些新的语法来明确指定我们需要将所有权转移给 lambda,我现在正在考虑以下语法:

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:

我将展示我对 movecopy 的实现,如下所示:

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 generalized capture 解决了这个问题在 C++14 中:

// a unique_ptr is move-only
auto u = make_unique<some_type>(some, parameters);

// move the unique_ptr into the lambda
go.run([u = move(u)]{do_something_with(u);});

关于c++ - 如何将 unique_ptr 捕获到 lambda 表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8236521/

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