C++ variable visable scopes and strems

为君一笑 提交于 2019-12-12 06:09:02

问题


I am newbie in C++ and can't understand some behavior. Have function below and in this case it works.

bool Network::doRequest(HTTPRequest& request, string path, string content) {
  HTTPResponse response;
  istream* respStreamPtr;
  session->sendRequest(request);
  respStreamPtr = &session->receiveResponse(response);
  if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
  {
    credentials->authenticate(request, response);
    session->sendRequest(request);
    respStreamPtr = &session->receiveResponse(response);
  }
  if (response.get("Content-Encoding") == "deflate") {
    Poco::InflatingInputStream inflater(*respStreamPtr);
    respStreamPtr = &std::istream(inflater.rdbuf());
    Logger::dumpStream(*respStreamPtr);
  }
  return true;
}

But if move string Logger::dumpStream(*respStreamPtr); out of the if block. Like this:

  if (response.get("Content-Encoding") == "deflate") {
    Poco::InflatingInputStream inflater(*respStreamPtr);
    respStreamPtr = &std::istream(inflater.rdbuf());
  }
  Logger::dumpStream(*respStreamPtr);

It's stop to work!!! Condition (response.get("Content-Encoding") == "deflate") always true; So trouble with visibility stream content in block. But I can't understand what I do wrong. Help me please.

P.S. In both case no exception. In second case just no data in file somefile.txt. In first case file somefile.txt has inflated data from http request.

void Logger::dumpStream(std::istream& inputStream) {  
  fstream outStream("somefile.txt", ios_base::trunc | ios_base::out | ios_base::binary);
  outStream << inputStream.rdbuf();
  outStream.close();
}

回答1:


I'm not familiar with the classes you're using, but it seems very likely that the problem is Poco::InflatingInputStream inflater is going out of scope.

Inside the if statement:

if (response.get("Content-Encoding") == "deflate") {
   Poco::InflatingInputStream inflater(*respStreamPtr);
   respStreamPtr = &std::istream(inflater.rdbuf());
} 

respStreamPtr is being pointed at a stream which uses a buffer from your inflater object. Once the if statement closes, that buffer is no longer valid and therefore you can't use your respStreamPtr outside.



来源:https://stackoverflow.com/questions/43858882/c-variable-visable-scopes-and-strems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!