为什么我不能移动std :: ofstream?

时间:2015-02-27 22:48:41

标签: c++ c++11 gcc clang fstream

在SO上查看以前的答案,似乎虽然std::ostream不可移动,但std::ofstream应该是。{1}}。但是,这段代码

#include <fstream>

int main()
{
    std::ofstream ofs;
    std::ofstream ofs2{std::move(ofs)};
}

似乎没有在我尝试的任何版本的gcc或clang中编译(使用--std = c ++ 11或--std = c ++ 14)。编译器错误有所不同,但这是我得到的gcc 4.9.0

6 : error: use of deleted function 'std::basic_ofstream::basic_ofstream(const std::basic_ofstream&)'

根据标准,这是预期的行为吗?

请注意,之前曾问过一个非常相似的问题(Is std::ofstream movable?),但从那时起标准似乎发生了变化(详见 Why can't std::ostream be moved?)渲染过时的答案。当然,这些答案都没有解释为什么上面的代码不能编译。

在尝试使用ofstream的容器时遇到此问题,由于上述情况而无效。

1 个答案:

答案 0 :(得分:17)

根据标准

  

27.9.1.11 basic_ofstream构造函数

或者,它的“可读”版本http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstreamstd::basic_ostream<>有一个移动构造函数,所以代码应该编译。

clang ++ 3.5使用-std=c++11-std=c++1y对其进行编译。 gcc5也编译它,所以可能它没有在libstdc ++中实现为gcc&lt; 5

有趣的是,在gcc的stdlibc ++实现中没有提到缺少移动语义https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2014

有关错误报告,请参阅https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316,感谢@BoBTFish指出。确认问题已在gcc5中修复。