如何返回标准文件流

Gas*_*sim 1 c++ g++ std

我正在为我的应用程序开发一个“文件系统”来处理文件操作,例如列出、创建、删除文件和目录以及获取文件数据。我想为此使用 std::fstream ,因为它比 C FILE Handler 更安全、更容易格式化。但是我无法从函数返回流对象(它没有副本 c'tor)并且当我尝试返回引用时我收到警告(我不是警告并不意味着那么多,但我正在尝试修复我的应用程序中所有可能的警告,直到现在我都做了):“警告:返回对临时的引用”。我能做什么?如果有人遇到这种情况并找到了更好的处理方法,请告诉。

编辑:

std::ofstream &Filesystem::createFile(const String &str) {
   std::ofstream file(str);
   return file;
}
Run Code Online (Sandbox Code Playgroud)

这就是我正在努力实现的目标。但由于警告,我正在寻找另一种方式。

提前致谢,
Gasim Gasimzada

Nim*_*Nim 5

使用智能指针,类似的东西(或较新的std::unique_ptr,等等)

std::auto_ptr<std::iostream> foo()
{
  return std::auto_ptr<std::iostream>(new fstream(...));
}
Run Code Online (Sandbox Code Playgroud)

  • +1。我个人会在很多情况下找到指向 `std::iostream` 的指针,因为它更通用。 (2认同)