O'Reilly logo

Boost.Asio C++ Network Programming by John Torjo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Staying alive

Say, you do the following operation:

io_service service;
ip::tcp::socket sock(service);
char buff[512];
...
read(sock, buffer(buff));

In this case, sock and buff must both outlive the call to read(). In other words, they must be valid after the call to read() returns. This is just what you'd expect; all arguments you pass to a function should be valid inside the function. Things get more complicated when we go asynchronous:

io_service service;
ip::tcp::socket sock(service);
char buff[512];
void on_read(const boost::system::error_code &, size_t) {}
...
async_read(sock, buffer(buff), on_read);

In this case, sock and buff must outlive the read operation itself, which we don't know when will happen, since it's asynchronous.

When using socket ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required