Why can't std::ostream be moved?

心不动则不痛 提交于 2019-11-26 12:25:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20774587/why-cant-stdostream-be-moved

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!