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 物件,可選地釋放字元陣列(虛公共成員函式) |
[虛擬函式] |
向輸出序列追加一個字元,如果緩衝區是動態且未凍結的,則可能重新分配或初始分配緩衝區 (虛保護成員函式) |