MST
星途 面试题库

面试题:C++ 自定义流缓冲区的实现

假设你需要实现一个自定义的流缓冲区,用于记录写入其中的数据长度并打印。请描述实现思路,包括继承的类、需要重写的关键函数以及如何将自定义流缓冲区与一个流对象(如ostringstream)关联起来。
36.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 继承的类
    • 应继承自std::streambuf类。std::streambuf是C++ 输入输出流库中负责缓冲区管理的基类。
  2. 需要重写的关键函数
    • overflow(int_type c = traits_type::eof())
      • 此函数在缓冲区已满,需要向其中插入新字符时被调用。
      • 实现时,需要检查缓冲区是否还有空间,若没有则处理缓冲区数据(比如记录长度并打印),然后尝试为新字符开辟空间。
      • 示例代码(伪代码):
int_type overflow(int_type c = traits_type::eof()) {
    if (c != traits_type::eof()) {
        // 检查缓冲区是否已满,这里假设缓冲区大小固定为bufSize
        if (next_free - buffer >= bufSize) {
            // 记录当前缓冲区数据长度
            std::size_t length = next_free - buffer;
            std::cout << "Data length written so far: " << length << std::endl;
            // 处理缓冲区数据(比如清空缓冲区为新数据做准备)
            next_free = buffer;
        }
        *next_free++ = traits_type::to_char_type(c);
    }
    return c;
}
  • sync()
    • 此函数用于将缓冲区中的数据同步到外部存储(比如文件、字符串等)。
    • 在我们的场景下,需要确保缓冲区中剩余的数据也被正确处理(记录长度并打印)。
    • 示例代码(伪代码):
int sync() {
    if (next_free - buffer > 0) {
        std::size_t length = next_free - buffer;
        std::cout << "Data length in buffer during sync: " << length << std::endl;
        // 可以选择清空缓冲区
        next_free = buffer;
    }
    return 0;
}
  1. 将自定义流缓冲区与ostringstream关联起来
    • 可以使用ostringstreamrdbuf()成员函数。
    • 示例代码:
#include <sstream>
#include <iostream>

class MyStreamBuf : public std::streambuf {
    // 上面定义的overflow和sync函数等
};

int main() {
    MyStreamBuf myBuf;
    std::ostringstream oss;
    oss.rdbuf(&myBuf);
    oss << "Hello, World!";
    return 0;
}

在上述代码中,通过oss.rdbuf(&myBuf)将自定义的MyStreamBufostringstream对象oss关联起来,这样oss输出的数据就会经过MyStreamBuf,进而触发我们重写的函数来记录数据长度并打印。