and cout maintain synchronization with the C I/O functions, right? Or is it just their implementation? Because if it's the former, there is a solution.
Interface is not implementation. Interface denotes what service a library provides, and implementation is how the service is performed internally. A stateless interface can have a stateful implementation. Consider a read-only caching database driver. A stateful interface can have a stateless implementation. Consider printf — the function alters the underlying IO state, while the implementation of printf itself is stateless [1]. Back to the problem, cin syncs with stdio by default, which means the *implementation* of cin is stateful. However, as an external user, you don't really care about the internal things [2]. What you actually care is the interface. cin introduces iostate, which effectively make the *interface* stateful. Now the state is exposed to external users, which means you have to think about the state between calls. To recapitulate, states are bad, but states are unavoidable when performing IO. As an I/O library author, you can add internal states to achieve syncing/caching or whatever. However, it's not wise to add states to your external interface to torture the library users. [1]: okay, I know that FILE has internal caching, but that's working at a lower layer. For the layer of formatting text, printf is stateless. [2]: unless you're not satisfied with the performance, see std::ios_base::sync_with_stdio.
Обсуждают сегодня