11

I have this code and don't know if what I would like to achieve is possible.

_acceptor.async_accept(
    _connections.back()->socket(),
    [this](const boost::system::error_code& ec)
    {
        _connections.push_back(std::make_shared<TcpConnection>(_acceptor.get_io_service()));
        _acceptor.async_accept(_connections.back()->socket(), this_lambda_function);
    }
);

Once a socket is accepted, I would like to reuse the handler (aka the lambda function). Is this possible? Is there a better way to accomplish this?

3
  • +1 Very interesting question. I hadn't thought of that before. Commented Apr 8, 2012 at 19:21
  • 1
    groups.google.com/group/comp.lang.c++.moderated/browse_thread/… Commented Apr 8, 2012 at 19:27
  • Not related to your question, but you should know that leading underscores (and two adjacent underscores) are reserved and shouldn't be used for application identifiers. Commented Apr 10, 2012 at 23:44

1 Answer 1

9

You have to store a copy of the lambda in itself, using std::function<> (or something similar) as an intermediary:

std::function<void(const boost::system::error_code&)> func;
func = [&func, this](const boost::system::error_code& ec)
{
    _connections.push_back(std::make_shared<TcpConnection>(_acceptor.get_io_service()));
    _acceptor.async_accept(_connections.back()->socket(), func);
}

_acceptor.async_accept(_connections.back()->socket(), func);

But you can only do it by reference; if you try to capture it by value, it won't work. This means you have to limit the usage of such a lambda to uses were capture-by-reference will make sense. So if you leave this scope before your async function is finished, it'll break.

Your other alternative is to create a proper functor rather than a lambda. Ultimately, lambdas can't do everything.

Sign up to request clarification or add additional context in comments.

1 Comment

@balki: No. It is legal in C/C++ to initialize a variable with an expression that uses the variable name. However, this is shut off when dealing with auto variables since the variable name doesn't have a type until the expression's type can be determined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.