Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 closure shared_ptr

Tags:

c++

c++11

lambda

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

like image 442
José Avatar asked Oct 09 '15 08:10

José


3 Answers

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);
like image 130
ForEveR Avatar answered Nov 01 '22 06:11

ForEveR


Generally speaking, you want to create a shared_ptr<X> via make_shared, initializing the X object with some Y object. Then generally the code to do that is

auto ptr = make_shared<X>(someY);

In your case, X is the std::function type, and the someY is your lambda. Once you have that, it's pretty straight forward:

auto funPtr = std::make_shared<function<void()>>( [](){ std::cout << "Hello World!\n"; } );
(*funPtr)();
like image 25
Arne Mertz Avatar answered Nov 01 '22 08:11

Arne Mertz


You can do it in two ways:

std::function<void()> lambda = [](){};
auto heapPtr = std::make_shared<std::function<void()>>(lambda);
auto heapPtr2 = new std::function<void()>(lambda);

You might also find the following questions useful:

  • C++11 lambda implementation and memory model
  • In C++11 lambda syntax, heap-allocated closures?
like image 1
SingerOfTheFall Avatar answered Nov 01 '22 07:11

SingerOfTheFall