std::strstreambuf::freeze
来自 cppreference.com
< 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 对象,选择性地释放字符数组(虚拟公有成员函数) |
[虚拟] |
将字符追加到输出序列,如果动态且未冻结,则可能会重新分配或最初分配缓冲区 (虚拟受保护的成员函数) |