与在堆上分配内存的 std::string
和 std::ofstream
相比,包含 std::cout
的程序不会' 似乎有任何堆分配。我知道 std::ostream
继承了 xalloc,iword
和 pword
.后两者描述它们确实具有某种内存管理。
First, allocates or resizes the private storage (dynamic array of long or another indexable data structure) sufficiently to make index a valid index, then returns a reference to the long element of the private storage with the index index.
但是 valgrind 似乎表明没有任何堆分配。
- 这种分配/调整大小何时发生?
std::ostream
的内部使用 new 和 delete 还是 malloc 和 free?
最佳答案
std::ostream
是一个基类,它允许派生类 Hook 到它的 std::streambuf
中。
因此,std::ostream
可以看作是 std::streambuf
指针(以及指向它的语言环境和格式信息的指针)的包装器。
std::streambuf
本身是一个带有一堆虚函数的基类,它本身不分配内存——派生类在实现它时会分配内存。例如,std::filebuf
实现了 std::fstream
的流缓冲区,为文件 I/O 分配缓冲区。
据我所知,缓冲 I/O(使用或不使用 iostream)在堆上为其缓冲区分配内存,包括 std::cout
。标准输出流的缓冲区很早就分配(在 main 之前)并且在所有情况下都是如此。因此,当您使用或不使用 std::cout
时,您的程序不会使用更多或更少的内存。至少在 GNU/Linux 上使用 libstdc++6。其他实现可能使用以不同方式分配的特殊缓冲区。
关于c++ - ostream 是如何管理内存的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25834592/