std::strstreambuf::~strstreambuf
来自cppreference.com
| |
(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);
} // 析构函数调用于此,解分配缓冲区
{
std::strstreambuf buf(my_alloc, my_free);
std::ostream s(&buf);
s << 1.23 << std::ends;
std::cout << buf.str() << '\n';
// buf.freeze(false);
} // 析构函数调用于此,内存泄漏!
}
输出:
my_alloc(4096) called
1.23
my_free() called
my_alloc(4096) called
1.23