问题描述
我正在使用shared_ptr
来保存libcurl
写函数返回的数据。以下代码可以正常工作。
std::stringstream http_data;
...
curl_easy_setopt(curl,CURLOPT_WRITEDATA,&http_data);
...
*br->read_buffer = http_data.str();
read_buffer
是标准shared_ptr
的{{1}}。
但是有什么方法可以通过将string
传递到shared_ptr
来提高效率。我找不到可行的方法,但是我刚接触curl_easy_setopt
。
shared_ptr
解决方法
在我看来,最有效的方法是将std::string
传递到CURLOPT_WRITEFUNCTION
回调,然后仅在传输成功的情况下将std::string
与目标字符串交换。
类似这样的东西:
std::size_t bf_callback(char* ptr,size_t size,size_t num,void* userdata)
{
if(auto s = reinterpret_cast<std::string*>(userdata))
{
// only get here if userdata is not nullptr
s->append(ptr,ptr + (size * num));
return size * num;
}
return 0; // indicate error to framework
}
//...
std::string http_data; // working string
curl_easy_setopt(curl,CURLOPT_WRITEDATA,&http_data);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,&bf_callback);
CURLcode code = curl_easy_perform(curl);
if(code != CURLE_OK)
throw std::runtime_error(curl_easy_strerror(code));
// now we are safe to use the working std::string
std::swap(*br->read_buffer,http_data); // std::swap can't throw exception