vendredi 10 janvier 2020

Update element pointed by std::unique_ptr captures by reference in lambda function

There's a way to update the element pointed from a unique_ptr passed to a lambda by reference? For example:

std::unique_ptr<MyClass> pointer(new MyClass(0));

std::function<void()> f = [&pointer]()
    {
       pointer->MyClass_print_int();
    };

f(); // print 0
pointer.reset(new MyClass(5));
f(); // want to print 5

I know that in this way I pass to lambda the reference to the old one element and print 0 twice. There's a mechanism (I'm thinking to make_unique but I'm not sure and I'm working with c++11) to make working the code below? Thanks!

Aucun commentaire:

Enregistrer un commentaire