José José - 1 year ago 155
C++ Question

C++11 closure shared_ptr

What is the syntax to create heap allocated closure manage by shared_ptr. I want to pass closures to functions and be able to pass nullptr. Seems like using a

shared_ptr< ::std::function<void()>
but I cannot figure the syntax to initialize that from a lambda expresion

Answer Source

It should be something like

auto lambda = []() { /* do something usefull */ };
auto p = std::make_shared<std::function<void()>>(lambda);

But actually you may no need shared_ptr, since function can be constructed from nullptr.

std::function<void()> fnc(nullptr);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download