在异步操作中移动复制字符串的最佳方法?

问题描述 投票:0回答:2

考虑到下面的例子,在异步操作中移动复制字符串的最佳方式是什么?

void Client::connect(const std::string& hostname, const std::string& port, const std::string& string) {
  auto socket_ = std::make_shared<net::ip::tcp::socket>(_io_context);
  net::ip::tcp::resolver resolver_(_io_context);
  auto endpoints_ = resolver_.resolve(hostname, port);

  net::async_connect(*socket_, endpoints_, [socket_, string](sys::error_code ec, net::ip::tcp::endpoint) {
    if(!ec) {
      std::make_shared<Session>(std::move(*socket_), std::move(string))->start();
    }
  });
}

Session::Session(net::ip::tcp::socket socket, const std::string& string)
  : _socket(std::move(socket)), _string(std::move(string)) {

}
c++ string boost-asio move-semantics
2个回答
1
投票

只需将字符串按值传递并移动,既干净又高效。

void Client::connect(const std::string& hostname, const std::string& port, std::string string) {
  auto socket_ = std::make_shared<net::ip::tcp::socket>(_io_context);
  net::ip::tcp::resolver resolver_(_io_context);
  auto endpoints_ = resolver_.resolve(hostname, port);

  net::async_connect(*socket_, endpoints_, [socket_, string{std::move(string)}](sys::error_code ec, net::ip::tcp::endpoint) mutable {
    if(!ec) {
      std::make_shared<Session>(std::move(*socket_), std::move(string))->start();
    }
  });
}

Session::Session(net::ip::tcp::socket socket, std::string string)
  : _socket(std::move(socket)), _string(std::move(string)) {

}

特别注意lambda捕获中允许将对象移动到lambda中的语法。

© www.soinside.com 2019 - 2024. All rights reserved.