What is [this, self] before handler assignment means in Boost library asio example?

StackOverflow https://stackoverflow.com/questions/21141116

  •  28-09-2022
  •  | 
  •  

Вопрос

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

Это было полезно?

Решение

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).

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top