I have a situation where I need to assign a unique ptr value from within a lambda function.
std::unique_ptr<SomeType> unique_ptr_obj;
// Lambda below has fixed return type.
bool var = ()[unique_ptr_obj=std::move(unique_ptr_obj)]-> bool {
unique_ptr_obj = GetUniqueObject();
return true
} ();
// Should be able to use unique_ptr_obj
UseUniqueObject(unique_ptr_obj.get());
However, as expected unique_ptr_obj
is nullptr as it was moved into lambda. Is there a way I can populate unique_ptr_obj
from within a lambda and be able to reuse it later ?
Any suggestions on how to accomplish this ? Should I convert unique_ptr_obj
to shared_ptr
?
CodePudding user response:
You should change the declaration of your lambda to capture unique_ptr_obj
by reference:
bool var = [&unique_ptr_obj]() -> bool {
// Whatever the next line does, now it changes that variable by reference.
// Otherwise you were changing a local copy.
unique_ptr_obj = GetUniqueObject();
return true;
} ();
CodePudding user response:
You don't want to share ownership. Or maybe you do, but it won't help with the lambda assigning something to unique_ptr_obj
, hence using a shared_ptr
is not the solution.
You also do not want to move from unique_ptr_obj
. Sloppy speaking, moving from something means leaving it in an empty state.
If you want a function to modify its argument then you pass by reference. If you want a lambda to modify something in the outer scope you let it capture it by reference.
This is the same whether its an int
or a unique_ptr
:
int x = 0;
bool value = [&x]() { x = 42; return true; } ();
// ^^ capture x by reference
assert(x == 42);