Question

I have never seen such syntax before "[this, self]", I used to program C and did a bit with C++, and now learning C++11 and Boost library, the compiler is happy with, but I can't figure out how it works and what it does.

void do_read()
  {
    auto self(shared_from_this());
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        [this, self](boost::system::error_code ec, std::size_t length)
---------^
        {
          if (!ec)
          {
            do_write(length);
          }
        });
  }

It comes from Boost library Async Echo server example in this link

Was it helpful?

Solution

That is the capture-list of the lambda. It is capturing the variable this (pointer) and the variable self declared one line above.

    [...](...){...}
//    A    B    C

The above is simplified syntax for the lambda in your code. A is the capture-list mentioned above (used to "capture" variables from the current scope). B is the argument list (just like in a function) and C is the body (again, like a function).

OTHER TIPS

This lambda capture in order to make sure the session object outlives the asynchronous operation: as long as the lambda is alive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top