如何在野兽中重用http :: response

问题描述

我想定期从网站上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函数实例化一个解析器,该解析器(通过移动)拥有所有响应资源的所有权。无论如何,它在其构造函数中无条件清除消息对象:

enter image description here

您可以使用调试器通过this之类的简单测试器来跟踪这些行,这正是我所做的。


¹最终,消息被移回传递的响应对象中,因此可以解决

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...