“std::ostream”没有名为“close”的成员

‘std::ostream’ has no member named ‘close’

std::ostream没有成员函数close()。什么类型的流不应该被允许关闭?

举个例子,也许我想关闭 std::cout 以防止进一步写入它。

std::cout.close(); // ‘std::ostream’ has no member named ‘close’

如果我使用的是 C 库,我可以关闭 stdout

fclose(stdout); // no problem

那么从 std::ostream 中删除 close() 成员的想法是什么?


相关:

close()函数作为std::ostream的成员是没有意义的。第一个例子是 std::ostringstream 继承自 std::ostream。关闭字符串有意义吗? std::ostream 的唯一成员是 input/output.

的全局对象

文件流具有 close() 功能,因为能够将资源释放到环境中很重要。但是,由于有其他 class 继承自此基础 class 而不需要此功能,因此将其作为 std::ostream 的一部分是没有意义的,那就是为什么它只在文件流中使用。

这是一种伪造的方法:

void ostream_fake_close( std::ostream & os )
   {
   os.flush();
   static std::stringstream closed_flag;
   cerr<<(os.rdbuf()==closed_flag.rdbuf()?"closed":"open")<<"\n";
   os.rdbuf(closed_flag.rdbuf());
   cerr<<(os.rdbuf()==closed_flag.rdbuf()?"closed":"open")<<"\n";
   }

未来对流的写入将被重定向到 closed_flag 缓冲区。您可以通过定期 resetting it:

来限制缓冲区的大小
closed_flag.str("");

真正的关闭会在对象销毁时自动发出。

除了 Meneldal 的出色回答。

如果您以后需要访问某些类型的资源,不释放资源仍然会导致问题。 如果出于某种原因您不想使用 ofstream(它有一个 close 方法),请坚持使用 ostream。你可以让它超出范围。

示例:

std::string FilePath = "C:/Test/MyFile.ext";

{  // <== Note the start of scope.

        // Writing a file using ostream as by example given by cplusplus.com reference.
        std::filebuf outfb;
        outfb.open(FilePath, std::ios::out);
        std::ostream os(&outfb);

        /* Do your stuf using 'os' here. */

}  // <== Note the end of scope.

/* Here, the resource is freed as if you would have called close. */
/* Rest of code... */

更新: 但是,现在我想起来了,在这种情况下 std::filebuf 提供了 close 方法,这也可以解决您的问题。