Namespaces
Variants

std::strstreambuf:: freeze

From cppreference.net
void freeze ( bool freezefl = true ) ;
(C++98 中已弃用)
(C++26 中移除)

如果缓冲区使用动态分配,将流的冻结状态设置为 freezefl

当流被冻结时, overflow() 不会重新分配缓冲区,且 destructor 不会释放缓冲区(从而导致内存泄漏)。

目录

参数

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 的公开成员函数)
[virtual]
销毁 strstreambuf 对象,可选择释放字符数组
(虚公开成员函数)
[virtual]
向输出序列追加字符,若为动态且未冻结则可能重新分配或初始分配缓冲区
(虚保护成员函数)