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?
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.
std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With