Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a unique_ptr into a lambda expression?

I have tried the following:

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

But it does not compile. Any ideas?

UPDATE:

AS suggested, some new syntax is required to explicitly specify we need to transfer the ownership to the lambda, I am now thinking about the following syntax:

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

Would it be a good candidate?

UPDATE 1:

I will show my implementation of move and copy as following:

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. } 
like image 438
Earth Engine Avatar asked Nov 23 '11 02:11

Earth Engine


People also ask

Can unique_ptr be passed to function?

Because the unique pointer does not have a copy constructor. Hence you cannot pass it by value, because passing by value requires making a copy.

Can unique_ptr be copied?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.


1 Answers

This issue is addressed by lambda generalized capture in 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);}); 
like image 160
mattnewport Avatar answered Sep 22 '22 03:09

mattnewport