[英]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.如果我使用 unique_ptr 来创建会话对象,就像在注释代码中一样,一切都很好。
But if I use just simple variables, like in current version.但是如果我只使用简单的变量,就像在当前版本中一样。 Then line
然后线
session.sendRequest(request) session.sendRequest(请求)
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. PS请求是对静态资源的简单 HTTP GET 请求。
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.这个构造函数的最后一行创建了一个名为
session
的局部变量,...当构造函数返回时它会立即被销毁,并且与同一成员的类成员无关。
So, when all is said and done, the session
member of this class instance remains uninitialized.因此,当一切都完成后,该类实例的
session
成员保持未初始化状态。 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.但是,由于 HTTPClientSession 没有可用的赋值运算符,您唯一的选择是继续使用
unique_ptr
,或者重构构造函数,以便它在其初始值设定项列表中构造类成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.