使用libcurl将重新记录的数据存储在shared_ptr

问题描述

我正在使用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