Reputation: 1019
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.
Upvotes: 4
Views: 787
Reputation: 19043
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.
Upvotes: 5