How can I use lambda function within itself?

人走茶凉 提交于 2021-02-06 16:00:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10065666/how-can-i-use-lambda-function-within-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!