简体   繁体   中英

Why fstream is not inherited from ifstream and ofstream in c++?

ifstream and ofstream is for input and output in file, and fstream can do task of both them but not inherited from either of ifstream and ofstream , is this code repetition or something else?

fstream的层次结构

You'd have to ask the author, Bjarne Stroustrup, for a definitive answer. In his original paper on iostreams published in USENIX Proceedings of 1985, he seems to put a lot of emphasis on efficiency:

Inline expanded functions are used for the basic operations (like "put a character into a buffer"), so the basic overhead tend to be one function call per simple object (integer, string, etc.) written (or read) plus one function call per buffer overflow.

So that could be the reason.

I guess you could extract common file I/O functionality into a mixin, but that would require virtual inheritance in order to allow for the diamond inheritance, which would add an extra indirection when accessing the underlying basic_filebuf .

In addition, as a file read/write mode normally cannot be changed once the file is opened, being able to cast fstream to ifstream or ofstream would create inconsistencies as you could get a writable ifstream or a readable ofstream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM