【发布时间】:2013-06-27 20:59:27
【问题描述】:
我将stringstream 的缓冲区设置为 5 字节缓冲区。只有当我调用sputn 时,它才能读取比我想要的更多的字符。这是为什么呢?
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
char buf[5];
ss.rdbuf()->pubsetbuf(buf, sizeof buf);
ss.rdbuf()->sputn("hello world", 12);
std::cout << ss.rdbuf(); // prints "Hello world"
}
【问题讨论】:
-
欢迎来到 C。C 中没有任何东西可以阻止你在脚下射击自己。这意味着 c++ 不会为您进行边界检查。
-
@andre:虽然这不是原始数组访问,但这是
std::basic_ostream的成员。它真的不应该写通过数组的末尾。 -
@MooingDuck 我不认为
sputn有任何保证它不会写入缓冲区之外。 -
@andre:排序。
If the output sequence write position is not available, returns overflow(traits::to_int_-type(c)).另一方面,pubsetbuf似乎不需要记住它的缓冲区是多少位,因此它会声称写入位置始终可用>。 -
@MemyselfandI,你用的是什么编译器?我想知道在这种情况下编译器的行为是合理的......