问题描述
我想定期从网站上http获得一些价值。 与野兽,代码就像:
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get,target,version};
req.set(http::field::host,host);
req.set(http::field::user_agent,BOOST_BEAST_VERSION_STRING);
http::response<http::string_body> res;
while (true) {
// Send the HTTP request to the remote host
http::write(stream,req);
res = {};
// Receive the HTTP response
http::read(stream,buffer,res);
// Write the message to standard out
std::cout << res << std::endl;
}
但是在循环中,
res = {}
创建了一个临时对象,进行了一次移动/复制分配并销毁了该临时对象。 我想知道是否有更好的方法来避免这些不必要的费用。
解决方法
只需删除有问题的行并将res
的声明移到while
循环内即可。 res
随后将在每次循环时创建和销毁:
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get,target,version};
req.set(http::field::host,host);
req.set(http::field::user_agent,BOOST_BEAST_VERSION_STRING);
while (true) {
// Send the HTTP request to the remote host
http::write(stream,req);
// Receive the HTTP response
http::response<http::string_body> res;
http::read(stream,buffer,res);
// Write the message to standard out
std::cout << res << std::endl;
}
,
您可以将res = {};
替换为res.clear();
或将其完全删除。
免费read
函数实例化一个解析器,该解析器(通过移动)拥有所有响应资源的所有权。无论如何,它在其构造函数中无条件清除消息对象:
您可以使用调试器通过this之类的简单测试器来跟踪这些行,这正是我所做的。
¹最终,消息被移回传递的响应对象中,因此可以解决