C ++可变可见范围和strem [英] C++ variable visable scopes and strems

查看:187
本文介绍了C ++可变可见范围和strem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,无法理解某些行为. 在下面有功能,在这种情况下它可以工作.

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;
}

但是,如果将字符串 Logger :: dumpStream(* respStreamPtr); 移出if块.像这样:

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);

上班了!!! 条件(response.get("Content-Encoding")=="deflate")始终为true; 因此,在块中的可见性流内容方面存在麻烦. 但是我不明白我做错了什么. 请帮帮我.

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.在两种情况下都不例外.在第二种情况下,文件somefile.txt中没有数据. 在第一种情况下,文件somefile.txt具有来自http请求的虚假数据.

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();
}

推荐答案

我对您使用的类不熟悉,但是问题很可能是Poco::InflatingInputStream inflater超出了范围.

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.

在if语句中:

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

respStreamPtr指向使用您inflater对象中的缓冲区的流.一旦if语句关闭,则该缓冲区不再有效,因此您不能在外部使用respStreamPtr.

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.

这篇关于C ++可变可见范围和strem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆