在开发网络库时,我最近注意到将 basic_streambuf::in_avail 挂件与 writesome 函数结合使用对于异步 I/O 来说非常方便。
我在网上搜索并检查了一些C++引用文献是否有满足这些要求的函数,但似乎我没有运气。提到类似功能的唯一来源是 Boost's Asio库,但是描述清楚地表明函数调用将阻塞,直到至少发送一个字节,这并不反射(reflect)我想要的行为。
为了详细说明我的问题,我根据 C++ N3337 出版物创建了一份草稿。
27.6.3.2.5 Put area [streambuf.pub.put]
streamsize in_depart();
Returns: If a write position is available, returns
epptr() - pptr()
. Otherwise returnsshowmanycp()
.27.6.3.4.5 Put area [streambuf.virt.put]
streamsize showmanycp();
Returns: An estimate of the number of characters which can be written to the sequence, or
-1
. If it returns a positive value, then successive calls tooverflow()
will not returntraits::eof()
until at least that number of characters have been written to the stream. Ifshowmanycp()
returns-1
, then calls tooverflow()
will fail.Default behavior: Returns zero.
Remarks: Uses
traits::eof()
.27.7.3.7 Unformatted output functions [ostream.unformatted]
streamsize writesome(char_type* s, streamsize n);
Effects: Behaves as an unformatted output function (as described in 27.7.3.7, paragraph 1). After constructing a sentry object, if
!good()
callssetstate(failbit)
which may throw an exception, and return. Otherwise writesn
characters designated bys
. Ifrdbuf()->in_depart() == -1
, callssetstate(badbit)
(which may throwios_base::failure
(27.5.5.4)), and writes no characters;— If
rdbuf()->in_depart() == 0
, writes no characters.— If
rdbuf()->in_depart() > 0
, writesmin(rdbuf()->in_depart(), n))
characters.Returns: The number of characters written.
最佳答案
我猜你误解了 in_avail()
的含义和readsome()
:所有这些都说明流已经读取了一个数据 block 并且缓冲区中仍然有字符。是的,理论上它可以做一些不同的事情,但特别是当从网络读取时,您不知道有多少数据可用,直到您尝试读取它。
同样,没有办法保证能够删除特定数量的字符: out.writesome(buf, n)
会怎样?意思是?如果你想让它意味着你抛弃了 n
字符输入 out
的缓冲区,您只需创建一个合适的流缓冲区并使用 write()
。保证n
字节是通过阻塞发送的,但是无法完成(至少对于 1 < n
)。不过,我猜你想要后者。
关于c++ - STL 中没有 basic_ostream 的 writesome 函数的理由是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458187/