std::strstreambuf::freeze
来自 cppreference.cn
< cpp | io | strstreambuf
void freeze( bool freezefl = true ); |
(在 C++98 中已弃用) (在 C++26 中移除) |
|
如果缓冲区使用动态分配,则将流的冻结状态设置为 freezefl。
当流被冻结时,overflow() 将不会重新分配缓冲区,并且 析构函数
将不会释放缓冲区(从而导致内存泄漏)。
目录 |
[编辑] 参数
freezefl | - | 设置冻结状态的新值 |
[编辑] 返回值
(无)
[编辑] 注解
每次调用 str() 都会冻结流以保留其返回的指针的有效性。为了允许析构函数释放缓冲区,需要显式调用 freeze(false)。
[编辑] 示例
在此示例中,底层数组的初始分配为 16 字节。
运行此代码
#include <iostream> #include <strstream> int main() { { std::strstream dyn; // dynamically-allocated read/write buffer dyn << "Test: " << 1.23; // note: no std::ends to demonstrate append behavior std::cout << "dynamic buffer holds " << dyn.pcount() << " characters: '"; std::cout.write(dyn.str(), dyn.pcount()) << "'\n"; // the buffer is now frozen, further output will not make the buffer grow dyn << "more output, hopefully enough to run out of the allocated space" << std::ends; std::cout << "After more output, it holds " << dyn.pcount() << " characters: '" << dyn.str() << "'\n"; dyn.freeze(false); // unfreeze before destructor } // memory freed by the destructor { char arr[20]; std::ostrstream st(arr, sizeof arr); // fixed-size buffer st << 1.23; // note: no std::ends to demonstrate append behavior std::cout << "static buffer holds " << st.pcount() << " characters: '"; std::cout.write(st.str(), st.pcount()); std::cout << "'\n"; st << "more output, hopefully enough to run out of the allocated space" << std::ends; std::cout << "static buffer holds " << st.pcount() << " characters: '"; std::cout.write(st.str(), st.pcount()); std::cout << "'\n"; } // nothing to deallocate, no need to unfreeze, }
输出
dynamic buffer holds 10 characters: 'Test: 1.23' After more output, it holds 16 characters: 'Test: 1.23more o' static buffer holds 4 characters: '1.23' static buffer holds 20 characters: '1.23more output, hop'
[编辑] 参见
禁用/启用自动重新分配 ( std::strstream 的公共成员函数) | |
禁用/启用自动重新分配 ( std::ostrstream 的公共成员函数) | |
[虚拟] |
析构一个 strstreambuf 对象,可选择释放字符数组(虚拟公共成员函数) |
[虚拟] |
向输出序列追加一个字符,如果动态且未冻结,则可能重新分配或初始分配缓冲区 (虚拟受保护成员函数) |