Skip to content

Commit f9e21e9

Browse files
committed
std::unique_ptr baby
Captures in lambdas are const by default. So in order to be able to move from them, we mark the entire lambda as mutable. Thus, member variables in our closure object are no longer const. Also, using a variable multiple times on the same line and one of the uses is modifying the variable is a no-no. Extract the pointer out of the unique_ptr before performing modifying operation.
1 parent 4a73735 commit f9e21e9

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

echo_server.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,22 @@ void handle_request(const std::error_code& error, tcp::socket socket) {
2727
return;
2828
}
2929

30-
auto request = std::make_shared<Request>(std::move(socket));
30+
auto request = std::make_unique<Request>(std::move(socket));
3131

3232
printf("Accepted connection\n");
3333

34-
asio::async_read_until(request->socket, request->buffer, '\n',
35-
[request](const auto &error, size_t bytes_transferred) {
34+
auto req = request.get();
35+
asio::async_read_until(req->socket, req->buffer, '\n',
36+
[request = std::move(request)](const auto &error, size_t bytes_transferred) mutable {
3637
if (error) {
3738
const auto &msg = error.message();
3839
printf("Error while reading: %s\n", msg.c_str());
3940
return;
4041
}
4142
printf("Received %zu bytes\n", bytes_transferred);
42-
asio::async_write(request->socket, request->buffer,
43-
[request](const auto &error, size_t bytes_transferred) {
43+
auto req = request.get();
44+
asio::async_write(req->socket, req->buffer,
45+
[request = std::move(request)](const auto &error, size_t bytes_transferred) mutable {
4446
if (error) {
4547
const auto &msg = error.message();
4648
printf("Error while writing: %s\n", msg.c_str());

0 commit comments

Comments
 (0)