I have a local lambda that is assigned to a field of an object called storage. This lambda will be called from elsewhere and my concern is whether this lambda is a dangling reference... isn't it destroyed when the function in which it is defined is exited?
not storage.on_open but rather its value (the lambda) which is destroyed at function get_storage() exit!! storage.on_open would be pointing to an automatic local lambda which is destroyed at function exit!
You are also correct it is assigned with a new lambda each time.. but my question is is the lambda destroyed on function exit? since after all the lambda is a local object...
Of course not. A lambda function is a function like any other. The difference is the way to access that function. The information how to access the lambda function is stored in a kind of structure. You create an object from these structure and it behaves like any other object. So when you have no object regarding the lambda you cannot call it anymore.
The lambda function itself runs as long as it runs. Regardless whether its access object still exists or not. Or any other object that matters.
A lambda expression, when evaluated, results in a function object (the closure object); an object of a class type with an implicitly declared (possibly trivial) destructor.
The closure object is destroyed when its logical life-time ends.
A lambda-expression provides a concise way to create a simple function object.
A lambda-expression is a prvalue whose result object is called the closure object. https://eel.is/c++draft/expr.prim.lambda#general-1
>The closure object is move assigned to storage.on_open; it does not matter that the life-time of the moved from object would end at function exit.
storage.on_open is a field of type std::function<void(sqlite3*)> of an object. How do I know it is moved assigned?
I looked at the implementation of std::function and found something answering my own question:
The standard specifies that std::function<> stores a copy of the CopyConstructibleCallable target. (Uses dynamically allocated memory to hold the copy, except for small targets).