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 ?
>Solution :
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;
} ();