std::strstreambuf::~strstreambuf
来自 cppreference.cn
< cpp | io | strstreambuf
virtual ~strstreambuf(); |
(在 C++98 中已弃用) (在 C++26 中已移除) |
|
销毁一个 std::strstreambuf
对象。如果该对象正在管理一个动态分配的缓冲区(缓冲区状态为“已分配”),并且如果该对象未被冻结,则使用构造时提供的或 delete[] (如果没有提供) 的释放函数来释放缓冲区。
[编辑] 参数
(无)
[编辑] 注释
此析构函数通常由 std::strstream 的析构函数调用。
如果在动态 strstream
上调用了 str() 并且之后没有调用 freeze(false)
,则此析构函数会造成内存泄漏。
[编辑] 示例
运行此代码
#include <iostream> #include <strstream> void* my_alloc(size_t n) { std::cout << "my_alloc(" << n << ") called\n"; return new char[n]; } void my_free(void* p) { std::cout << "my_free() called\n"; delete[] (char*)p; } int main() { { std::strstreambuf buf(my_alloc, my_free); std::ostream s(&buf); s << 1.23 << std::ends; std::cout << buf.str() << '\n'; buf.freeze(false); } // destructor called here, buffer deallocated { std::strstreambuf buf(my_alloc, my_free); std::ostream s(&buf); s << 1.23 << std::ends; std::cout << buf.str() << '\n'; // buf.freeze(false); } // destructor called here, memory leak! }
输出
my_alloc(4096) called 1.23 my_free() called my_alloc(4096) called 1.23