Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store shared pointer in lambda to keep it alive

A struct like this is intended to be stored in a lambda:

struct MyStruct {
  void testfunction() {
    // Do something
  }
};

What I want is to construct a shared pointer from that and store this pointer in a lambda:

auto ptr = std::make_shared<MyStruct>();
std::function<void()> caller = [ptr](){
  ptr->testFunction();
}

The caller object is given to a function and is copied by that function. The ptr object goes out of scope. Is the shared pointer still alive when I pass the caller object around?

Is it guaranteed that ptr is stored in the lambda and the object is managed by that pointer as long as caller exists or was returned? Are there any compiler optimizations if I do not call testFunction?

This problem is specific to a boost::asio problem where I want to pass some object withing an asynchronous handler.

like image 733
Gustavo Avatar asked Nov 01 '25 13:11

Gustavo


1 Answers

from cppreference

If the lambda-expression captures anything by copy (either implicitly with capture clause [=] or explicitly with a capture that does not include the character &, e.g. [a, b, c]), the closure type includes unnamed non-static data members, declared in unspecified order, that hold copies of all entities that were so captured.

So, in accordance with as-if rule, it is expected that your compiler will generate code which will behave like if you really have this copy and so object will be kept alive.

like image 193
Yola Avatar answered Nov 04 '25 04:11

Yola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!