使用 future 时获取 C2280(尝试引用已删除的函数)

Getting C2280 (attempting to reference a deleted function) when using future

我正在使用 poco 库,我正在尝试将它们包装到一个更好的 HTTPClient 中,我可以在几行中随处使用,并使它们异步。为此,我使用 std::future 和自定义响应结构。但是,出于某种原因,它告诉我它正在尝试引用已删除的函数。我没有删除任何东西,所以我真的不知道为什么会这样说。

httpclient.h

#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Exception.h>
#include <Poco/URI.h>
#include <future>
#include <map>

typedef struct response {
    std::istream& is;
    Poco::Net::HTTPResponse& response;
} RES;

class HttpClient {
public:
    static std::future<RES> get(Poco::Net::HTTPSClientSession& session, Poco::URI url, std::map<std::string, std::string> headers = {});
};

httpclient.cpp

#include "httpclient.h"

std::future<RES> HttpClient::get(Poco::Net::HTTPSClientSession& session, Poco::URI url, std::map<std::string, std::string> headers) {
    return std::async(std::launch::async, [&session, url, headers](){
        try {
            std::string path(url.getPathAndQuery());
            if (path.empty()) path = "/";

            Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
            request.add("Content-Length", "0");

            if (headers.size() > 0) {
                for (std::map<std::string, std::string>::const_iterator itr = headers.begin(); itr != headers.end(); ++itr) {
                    request.add(itr->first, itr->second);
                }
            }

            Poco::Net::HTTPResponse _res;
            session.sendRequest(request);
            std::istream& is = session.receiveResponse(_res);
            return RES { is, _res };
        }
        catch (Poco::Exception & exc) {
            OutputDebugStringA(exc.displayText().c_str());
        }
    });
}

main.cpp

Poco::Net::initializeSSL();

    Poco::URI uri("https://www.google.com");
    const Poco::Net::Context::Ptr context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
    Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

    std::future<RES> response = HttpClient::get(session, uri, {});
    response.get();

这是我得到的精确错误: C2280: response &response::operator =(const response &)': attempting to reference a deleted function future:line 332.

谢谢!

该错误告诉您无法复制 response 个对象,而您正试图这样做。

struct response { 
    std::istream& is; // can't be copied: istream( const istream&) = delete;
    Poco::Net::HTTPResponse& response; // also not copyable or movable
};

然而,您显示的代码中没有任何内容尝试这样做。

receiveResponse() return 是对 std::istream 的引用,如果它抛出就会出现问题。当你捕捉到异常时,你没有任何东西可以return,所以你不会 - 进入未定义行为的领域。

您不妨读取 async lambda 中的数据并将其直接存储在您的 RES 中。

#include <Poco/Exception.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/SecureStreamSocket.h>
#include <Poco/URI.h>

#include <future>
#include <iostream>
#include <map>
#include <vector>
#include <memory>

// a slightly modified version of your RES struct
struct RES {
    std::vector<std::string> data{}; // the document data

    // using a unique_ptr to make HTTPResponse easier to move
    std::unique_ptr<Poco::Net::HTTPResponse> 
        response = std::make_unique<Poco::Net::HTTPResponse>();

    bool ok = false;                 // if reading was done without an exception
};

class HttpClient {
public:
    static std::future<RES> get(Poco::Net::HTTPSClientSession& session,
                                Poco::URI url,
                                std::map<std::string, std::string> headers = {});
};

std::future<RES> HttpClient::get(Poco::Net::HTTPSClientSession& session,
                                 Poco::URI url,
                                 std::map<std::string, std::string> headers) {
    return std::async(std::launch::async, [&session, url, headers]() {

        RES res;

        try {
            Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET,
                                           url.getPathAndQuery(),
                                           Poco::Net::HTTPMessage::HTTP_1_1);

            // add request headers
            for(const auto&[field, value]:  headers)
                request.add(field, value);

            session.sendRequest(request);
            std::istream& is = session.receiveResponse(*res.response);

            // read document data
            std::string line;
            while(std::getline(is, line))
                res.data.push_back(line);

            res.ok = true; // reading was done without an exception
        } catch(Poco::Exception& exc) {
            std::cout << exc.displayText().c_str() << "\n";
        }

        // always return according to what you declared
        return res;
    });
}

用法示例:

class SSLInitializer {
public:
    SSLInitializer() { Poco::Net::initializeSSL(); }
    ~SSLInitializer() { Poco::Net::uninitializeSSL(); }
};

int main() {
    SSLInitializer sslInitializer;

    Poco::URI uri{"https://www.google.com/"};

    const Poco::Net::Context::Ptr context = new Poco::Net::Context(
        Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9,
        false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");

    Poco::Net::HTTPSClientSession sess(uri.getHost(), uri.getPort(), context);

    std::future<RES> fut_res = HttpClient::get(sess, uri);

    fut_res.wait();

    RES res = fut_res.get();
    std::cout << std::boolalpha << "Response OK: " << res.ok << "\n---\n";
    if(res.ok) {
        Poco::Net::HTTPResponse& header = *res.response

        std::cout << "HTTPResponse header:\n";
        for(const auto& [field, value] : header) {
            std::cout << field << " = " << value << "\n";
        }

        std::cout << "--- DOCUMENT DATA ---\n";
        for(const auto& s : res.data) {
            std::cout << s << "\n";
        }
    }
}

您遇到的问题是由于 class Poco::Net::HTTPResponse 不可复制。它的复制构造函数和赋值运算符都被声明为私有的。所以复制它是不可能的。

我确实认为为每个 http 请求生成一个新线程是过分的。我可以理解您想要这样做的原因,但您必须记住,创建新线程会涉及一些开销。你最好只使用 Poco classes,或者,如果你愿意,可以在它们上面使用一个东西包装器。通过为每个请求生成一个新线程,您的 http 请求可能 运行 变慢。

我可以建议对你的 struct RES 做一些小改动吗:

typedef struct response {
    Poco::Net::HTTPResponse::HTTPStatus status;
    std::string contents;
} RES;

此结构现在可用于在发出请求后保存来自 Poco::Net::HTTPResponse 对象的数据。然后借助辅助函数将 std::istream 的内容输出到 std::string:

std::string Gulp(std::istream& in)
{
    std::string response(std::istreambuf_iterator<char>(in), {});
    return response;
}

您可以在 main.cpp 中执行此操作:

Poco::Net::initializeSSL();
Poco::URI uri("https://www.google.com");
const Poco::Net::Context::Ptr context = new 
Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";

Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse _res;
session.sendRequest(request);
std::istream& is = session.receiveResponse(_res);
RES response{ _res.getStatus(), Gulp(is) };