Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] wrap lambda async_receive call
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-03-22 23:06:19

On 19/03/2015 19:16, Cheng Mo wrote:
> Hi Gavin:
> >Having said this, using lambdas can get tricky in real-world code, as
> >it's common to want to start the same read operation when the first
> >completes, and so on.
> Just like you said, will the code build a lambda expression when
> async_read() invoked ?
> So that "[=](const error_code& ec,size_t count" will be built servial
> times, it is kind of lavish for contructing the lambda expression, isn't ?

The compiler will build the code for a lambda only once regardless of
how many times it's called. But it also won't let you create a
recursive lambda, which is what you would need if you wanted to have a
read operation repeat itself when it completes (which is the most common

Well, actually that's not quite true -- you can type-erase a lambda via
std::function or similar and then call it recursively. But AFAIK you
can only do this when capturing by reference, and you can't safely do
that with a locally declared lambda when making async calls. So it's
not really useful in this context.

> It's better that build a function object in static. What do you think ?

Function objects have a similar lifetime issue, and making one static is
potentially dangerous if you could have multiple operations or
connections running concurrently. It's usually simplest to use a
private method of the containing class, which is what most of the
example code does.

(If you really want to hide it from clients of your class, then use the
PIMPL idiom.)

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at