c++ - `basic_streambuf::setbuf`的效果

标签 c++ c++11 language-lawyer

我的问题如下: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 of setbuf() are implementation-defined, except that setbuf(0, 0) are defined: if setbuf(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() for basic_filebuf and basic_stringbuf hardly impose any requirements on the semantics of setbuf() 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 of setbuf().

关于c++ - `basic_streambuf::setbuf`的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4349778/

相关文章:

c++ - 在流行的Coin-Change动态编程问题中遍历状态的正确顺序是什么?

c++ - 为什么用 clang 编译时 std::atomic<double> 没有实现?

c++ - QTimer::singleShot 仅在间隔为 0 时调用 lambda

c++ - malloc 分配的内存在什么时候获得类型?

c++ - 在 C++20 中,如果宏是 #undef'd,然后又是 #define'd,那么它是否被认为是 "active"?

c++ - 使用这种粉刺替代品会牺牲什么?

c++ - `std::set` 在每种情况下都会对元素进行排序吗?

c++ - 什么是抽象类没有数据成员的编译器生成的构造函数

c++ - time.h 实现代码在哪里?

c++ - 有人可以解释为什么我在这里收到 fatal error C1202 以及如何解决它吗?