简体   繁体   中英

Poco::Net::HTTPClientSession throw exception without unique_ptr

I have 2 version of code:

    // HTTP.h
    class HTTP
    {
    private:
      //unique_ptr<HTTPClientSession> session;
      HTTPClientSession session;

      bool doRequest(Poco::Net::HTTPRequest& request, const string& path, const string& content, string& responseBody);
    public:
      HTTP(const string& adress);
    }

    // HTTP.cpp

    HTTP::HTTP(const string& adress)
    {
      Poco::URI uri(
        adress.substr(0, 4) == "http" ? adress : "http://" + adress
      );
      //session = make_unique<HTTPClientSession>(uri.getHost(), uri.getPort());
      HTTPClientSession session{ uri.getHost(), uri.getPort() };
    }

    bool HTTP::doRequest(HTTPRequest& request, const string& path, const string& content, string& responseBody) {
      ...
      session.setTimeout(Timespan(5, 0));
      //std::ostream& requestStream = session->sendRequest(request);
      std::ostream& requestStream = session.sendRequest(request);
      ...
    }

If I use unique_ptr to create session object, like in commented code, everythings worls fine.

But if I use just simple variables, like in current version. Then line

session.sendRequest(request)

throw exception Connection refused

I do not understand why? Could you explein me please.

PS request it is simple HTTP GET request to static resource.

HTTP::HTTP(const string& adress)
{
  Poco::URI uri(
    adress.substr(0, 4) == "http" ? adress : "http://" + adress
  );

  HTTPClientSession session{ uri.getHost(), uri.getPort() };
}

The last line in this constructor creates a local variable named session , ... which gets immediately destroyed when the constructor returns, and has nothing to do with the class member of the same member.

So, when all is said and done, the session member of this class instance remains uninitialized. For comparison purposes:

session = HTTPClientSession{ uri.getHost(), uri.getPort() };

This would correctly initialize the class member, instead, as your obvious intent was. However, since HTTPClientSession does not have a usable assignment operator, your only option is to either continue using unique_ptr , or restructure the constructor so that it constructs the class member in its initializer list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM