为什么不能移动std :: ostream?

Die*_*ühl 56 c++ iostream c++11

显然,无法复制流.应该可以移动流.根据27.9.1.11 [ofstream.cons]段4有可能移动的构造std::ofstream(同为真std::ifstream,std::fstreamstd::*stringstream变体).例如:

#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") };
}
Run Code Online (Sandbox Code Playgroud)

试图运动std::ostream,例如,有一个工厂函数创建一个std::ofstream,一个std::ostringstream,或者根据参数不起作用通过了URN一些其他的流.std::ostream(std::basic_ostream实际上,类模板)protected根据27.7.3.1 [ostream] 有一个移动构造函数.

为什么不能自己std::ostream移动?

How*_*ant 58

最初他们是可移动的.结果证明这是我的一个设计缺陷,由Alberto Ganesh Barbati发现:

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

该问题显示了一些ostream移动和/或交换的示例,结果令人惊讶,而非预期.我确信这些类型不应该是公开移动的,也不应该通过这个问题进行交换.

  • 嗯.我看到了问题,但我不确定我是否同意解决方案是让它们不可移动.相反,应该更改实现,以便代码具有预期的行为(通过擦除流的实际类型,我假设).FWIW Dietmar提出了一个引人注目的用例,说明为什么溪流*应该可以移动(我以前遇到过同样的问题). (4认同)