我的问题如下:Martin York this 中的 claim , this , 和 this回答可以使用 basic_stringbuf::pubsetbuf
像这样从一段内存中读取 stringstream
:
char buffer[] = "123";
istringstream in;
in.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); // calls basic_stringbuf::setbuf
int num;
in >> num; // reads 123
不幸的是,我仔细研究了整个标准,看不出它在哪里可以保证工作。我看到的是这只是实现定义的。事实上,在 Microsoft 的实现(也许对其他人也是)这个调用没有任何效果。
这是我在上一个 C++0x 草案中找到的相关引用。对于 basic_streambuf::setbuf
[streambuf.virt.buffer]:
1 Effects: Influences stream buffering in a way that is defined separately for each class derived from basic_streambuf in this Clause (27.8.1.4, 27.9.1.5).
2 Default behavior: Does nothing. Returns this.
然而,在派生类中,它似乎保留了行为实现定义。对于 basic_stringbuf::setbuf
它说 [stringbuf.virtuals]:
1 Effects: implementation-defined, except that setbuf(0,0) has no effect.
对于 basic_filebuf::setbuf
它说 [filebuf.virtuals]:
12 Effects: If setbuf(0,0) [...], the stream becomes unbuffered. Otherwise the results are implementation-defined. “Unbuffered” [...]
就是这样。所以在我看来,一个有效的实现可以完全忽略这些调用(对于非空参数)。
我错了吗?标准的正确解释是什么? C++98/03/0x 有同样的保证吗?您是否有更多关于上述代码在哪些实现上起作用以及在哪些实现上不起作用的统计数据? basic_streambuf::setbuf
打算如何使用?
最佳答案
我相信它是实现定义的,并且您提供了相关的报价。
为了记录,这是Standard C++ IOStreams and locales ,不完全是我必须承认的最近的一本书,必须在标题为“几乎没有语义的函数 - setbuf()
”的部分中谈到这个主题:
The virtual member function
setbuf()
is a rather peculiar stream buffer member. Its semantics are basically undefined. For string stream buffers, the semantics ofsetbuf()
are implementation-defined, except thatsetbuf(0, 0)
are defined: ifsetbuf(0, 0)
is called on a stream before and I/O has occured on that stream, the stream becomes unbuffered, meaning that characters are directly transported to and from the file system. Otherwise, the results are implementation-defined.However, the specifications of
setbuf()
forbasic_filebuf
andbasic_stringbuf
hardly impose any requirements on the semantics ofsetbuf()
in other stream buffer types. At best, the general semantics can be defined as device and, in the case of user-defined stream buffer types, implementation-specific.The lack of any requirements frees you to redefine
setbuf()
for just about any purpose and in any way that fits into the predefined interface ofsetbuf()
.
关于c++ - `basic_streambuf::setbuf`的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4349778/