Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't std::ostream be moved?

Clearly, streams can't be copied. It should be possible to move streams. According to 27.9.1.11 [ofstream.cons] paragraph 4 it is possible to move construct an std::ofstream (the same is true for std::ifstream, std::fstream, and the std::*stringstream variants). For example:

#include <iostream> #include <fstream> #include <string>  std::ofstream makeStream(std::string const& name) {     return std::ofstream(name); }  int main() {     std::ofstream out{ makeStream("example.log") }; } 

Trying to move an std::ostream, e.g., to have a factory function creating an std::ofstream, an std::ostringstream, or some other stream according to a URN passed as argument doesn't work. std::ostream (well, the class template std::basic_ostream really) has a protected move constructor according to 27.7.3.1 [ostream].

Why can't std::ostream be moved itself?

like image 705
Dietmar Kühl Avatar asked Dec 25 '13 16:12

Dietmar Kühl


People also ask

What is std :: ostream?

The std::ostream , the std::istream or the std::iostream are base classes of stream types (e.g. std::stringstream , std::fstream , etc.) in the Standard Library. These classes are protected against instantiation, you can instantiate their derived classes only.

What does std :: move () do?

std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.

What happens when you to std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

Does std :: move make a copy?

std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.


1 Answers

Originally they were movable. This turned out to be a design flaw on my part, and discovered by Alberto Ganesh Barbati:

http://cplusplus.github.io/LWG/lwg-defects.html#911

The issue shows a few examples where ostream gets moved and/or swapped, and the results are surprising, instead of expected. I was convinced that these types should not be publicly movable nor swappable by this issue.

like image 194
Howard Hinnant Avatar answered Oct 14 '22 06:10

Howard Hinnant