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
Asked
Active
Viewed 676 times
8
José
- 3,041
- 8
- 37
- 58
4 Answers
4
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)();
Arne Mertz
- 24,171
- 3
- 51
- 90
1
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:
Community
- 1
- 1
SingerOfTheFall
- 29,228
- 8
- 68
- 105
0
I prefer putting shared_ptr inside the function object.
auto o = make_shared<MyData>();
return [o] ()
{
...
};
So, the data for the closure is on the heap and ref-counted while the handle can be copied and passed around. The data is cleaned up when the last handle is destroyed.
Velkan
- 7,067
- 6
- 43
- 87