在 Boost.asio C++11 示例中有片段 like the following :
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);
}
});
}
我明白为什么需要 self
指针来保持类存活(参见 this question ),但我不明白为什么 this
指针是 也捕获。是否只是为了让作者可以写 do_write(length)
而不是 self->do_write(length)
还是有别的原因?
最佳答案
如果没有捕获 this
,则不能从 lambda 内部调用类的方法(例如 do_write
)。或者访问成员变量。当然,您可以改为编写 self->do_write()
,但它既不优雅,也可能更慢(因为涉及到 shared_ptr
)。
关于c++ - 为什么要在 lambdas 中捕获 this 以及指向 this 的共享指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34719233/