Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign a unique_ptr value from within a lambda

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
} ();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading