VP.
VP.

Reputation: 16725

Are c++11 lambda targets statically created?

I have a following method:

using async_handler_t = std::function<void(boost::system::error_code, std::size_t)>;
async_handler_t deadlineHandler(boost::system::error_code &ec) {
    return [&ec, this](boost::system::error_code newEc, std::size_t) {
        ec = newEc;
        deadline_.cancel();
    };
}

This is simple asio deadline handler which stops the deadline timer and allows the io_service-run loop to continue (grabbed this from official asio timeout docs).

The question is about how much times the function itself is generated. I understand, that I return a functional object from this method (std::function object) which is created dynamically during runtime but is the target function created only once?

Upvotes: 0

Views: 37

Answers (2)

Quentin
Quentin

Reputation: 63124

The lambda expression implicitly declares a functor class, and creates an instance of it.
The generation of the class' type (and the code of its operator()) is, of course, done once at compile-time.
A new instance of this class (containing what the lambda captured) is created each time you call your function.

Upvotes: 0

The code inside the body of the lambda will only be compiled once and all instances of that lambda's closure object type will share the code. But each call to deadlineHandler will result in a new instance of the closure type being created, its members ec and this being initialised, and then a std::function object being created from that instance.

Upvotes: 1

Related Questions