c++ - 如何在引用超出范围后检测ptr是否仍在引用有效引用

标签 c++ pointers iostream ostream

我玩弄了一些流,但无法理解以下内容。

这里我们有一个基本的ostream ptr,它设置为不同的输出流,无论是coutcerr还是file

// ostream ptr
std::ostream* outstream;

// set output ostream
void setOutput(std::ostream & os)
{
  outstream = &os; 
}

// write message to ostream
void writeData(const std::string & msg)
{    
  *outstream << msg << '\n';
}

int main (int argc, char * const argv[]) 
{
  // init to std out
  setOutput(std::cout);
  writeData("message to cout");

  setOutput(std::cerr);
  writeData("message to cerr");

  std::ofstream fileout("test.txt", std::ofstream::out | std::ofstream::app);
  setOutput(fileout);
  writeData("message to file");
  //fileout.close();

  setOutput(std::cout);
  writeData("message2 to cout");

  return 0;
}

以上内容完美运行,展示了 c++ iostream 实现的强大功能。完美的。

但是,由于 setOutput 是通过引用设置的,因此被引用的对象必须保持在范围内。这就是问题出现的地方。如果 ofstream 或任何其他 ostream 无效,我想找出一种将输出默认为 std::cout 的方法。也就是说,被引用的对象已经或超出了范围。

例如:

// write message to ostream
void writeData(const std::string & msg)
{
  if (/*stream or memory is invalid*/)
    setOutput(std::cout);

  *outstream << msg << '\n';
}
// local fileout goes out of scope
void foo()
{
  std::ofstream fileout("test.txt", std::ofstream::out | std::ofstream::app);
  setOutput(fileout);
  writeData("message to file");
}

int main (int argc, char * const argv[]) 
{
  setOutput(std::cout);
  writeData("message to cout");

  foo();
  /* problem the local fileout is no longer referenced by the ostream ptr*/
  /* the following should be redirected to std::cout cuz of default*/
  writeData("message2 to cout");

  return 0;
}

foo() 返回到 main 函数之前,以上内容都很好。由于本地定义的 ofstream 不再可访问,因此出现了可怕的错误。

显然这是不可取的,用户应该意识到这一点。但是,我想将所有这些包装在一个日志记录类中,从而保持对象的状态有效,即使这种滥用可能发生。这将导致无效的访问冲突,很难找到。

具体问题。有什么方法可以确定 ostream ptr 或任何 ptr 是否仍在引用有效的对象或内存位置?

ps:我可以使用堆内存并使用智能指针做一些事情,但坦率地说,如果可能的话,我希望保持这种状态

最佳答案

Concrete question. Is there any way to figure out whether an ostream ptr or any ptr for that matter is still referencing a valid object or memory location?

没有。没有办法用原始指针来解决这个问题。至少在标准 c++ 中没有。

您需要保证被指向的对象只要被指向就一直保持事件状态。

用于提供该保证的常见模式是 RAII,如其他答案中所述。保证指针有效性的另一种方法是使用智能指针而不是原始指针。但是,这些与自动变量不兼容。

只要你能保证指针没有被取消引用,就可以继续指向死对象。这通常很难保证,因为如前所述,没有办法测试指向的对象是否存在。

关于c++ - 如何在引用超出范围后检测ptr是否仍在引用有效引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37036857/

相关文章:

c++ - 使用this指针可以吗?

c++ - 了解文件流标志/位

c++ - 确定类类型

c++ - 默认情况下,C++ 是否将二进制数读取为二进制补码?

c++ - 正确关闭boost线程

c++ - 在图像上放置图像

c - 垃圾值检索

c++ - C++ 中的这种未定义行为是从悬空指针调用函数吗

c++ - 无法将数字插入基于 char16_t 的自定义 C++ ostream/streambuf

c++ - 具有结构的简单程序。获取此 : invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator