高效的将数据从boost :: asio :: streambuf复制到std :: string [英] efficient copy of data from boost::asio::streambuf to std::string
问题描述
我需要将(boost :: asio::) streambuf的内容复制到std :: string。
I need to copy the content of a (boost::asio::)streambuf to an std::string.
以下代码可以工作,在_msg和临时std :: string之间有一个不必要的副本:
The following code works, but I think that there's an unnecessary copy between _msg and the temporary std::string:
Msg (boost::asio::streambuf & sb, size_t bytes_transferred) :
_nBytesInMsg (bytes_transferred)
{
boost::asio::streambuf::const_buffers_type buf = sb.data();
_msg = std::string(
boost::asio::buffers_begin(buf),
boost::asio::buffers_begin(buf) + _nBytesInMsg);
}
我尝试用以下代替:
_msg.reserve(_nBytesInMsg);
std::copy(
boost::asio::buffers_begin(buf),
boost::asio::buffers_begin(buf) + _nBytesInMsg,
_msg.begin()
);
在编译时,它不会将任何东西复制到_msg字符串。
While this compiles, it doesn't copy anything to the _msg string.
编译器(gcc4.4.7)会优化这种情况 - 例如将streambuf直接复制到_msg而不使用临时文件?
Will the compiler (gcc4.4.7) optimize this case - e.g. copy the streambuf straight to _msg without using a temporary?
是否有可能使用boost :: asio :: streambuf :: const_buffers_type来创建一个迭代器std :: copy工作?
Is there perhaps an iterator I can use with boost::asio::streambuf::const_buffers_type in order to make the std::copy work instead?
推荐答案
reserve
你认为它意味着什么。您可以确定阅读其文档的含义。它与 resize
不同;预留空间不会影响容器的大小。
reserve
doesn't mean what you think it means. You can work out for sure what it means by reading its documentation. It is not the same as resize
; reserving space does not affect the container's size.
您需要将元素实际插入到字符串中。执行此操作:
You need to actually insert elements into the string. Do this:
#include <algorithm> // for copy
#include <iterator> // for back_inserter
_msg.reserve(_nBytesInMsg); // about to insert _nBytesInMsg elements
std::copy(
boost::asio::buffers_begin(buf),
boost::asio::buffers_begin(buf) + _nBytesInMsg,
std::back_inserter(_msg)
);
这篇关于高效的将数据从boost :: asio :: streambuf复制到std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!