Go to the first, previous, next, last section, table of contents.

Why can't I assign one stream to another?

[ Thanks to Per Bothner and Jerry Schwarz for this section. ]

Assigning one stream to another seems like a reasonable thing to do, but it's a bad idea. Usually, this comes up because people want to assign to cout. This is poor style, especially for libraries, and is contrary to good object-oriented design. (Libraries that write directly to cout are less flexible, modular, and object-oriented).

The iostream classes do not allow assigning to arbitrary streams, because this can violate typing:

ifstream foo ("foo");
istrstream str(...);
foo = str;
foo->close ();  /* Oops! Not defined for istrstream! */

The original cfront implementation of iostreams by Jerry Schwarz allows you to assign to cin, cout, cerr, and clog, but this is not part of the draft standard for iostreams and generally isn't considered a good idea, so standard-conforming code shouldn't use this technique.

The GNU implementation of iostream did not support assigning to cin, cout, cerr, and clog for quite a while, but it now does, for backward compatibility with cfront iostream (versions 2.6.1 and later of libg++).

The ANSI/ISO C++ Working Paper does provide ways of changing the streambuf associated with a stream. Assignment isn't allowed; there is an explicit named member that must be used.

However, it is not wise to do this, and the results are confusing. For example: fstream::rdbuf is supposed to return the original filebuf, not the one you assigned. (This is not yet implemented in GNU iostream.) This must be so because fstream::rdbuf is defined to return a filebuf *.


Go to the first, previous, next, last section, table of contents.