为什么我不能移动std :: ofstream? [英] Why can't I move std::ofstream?
问题描述
看看之前的答案,看起来虽然 std :: ostream
不是可移动的, std :: ofstream
应该是。但是,此代码
Looking at previous answers on SO, it seems that while std::ostream
is not be movable, std::ofstream
should be. However, this code
#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
does not seem to compile in any version of gcc or clang I tried (with either --std=c++11 or --std=c++14). The compiler error varies somewhat, but here's what I get for gcc 4.9.0
6 : error: use of deleted function 'std::basic_ofstream::basic_ofstream(const std::basic_ofstream&)'
根据标准?
请注意,之前问过一个非常类似的问题(是std :: ofstream可移动吗?),但似乎标准已经改变了自那以后(详细在
为什么不能std :: ostream被移动?)渲染这些答案过时。当然,没有这些答案解释为什么上面的代码不编译。
Note that a very similar question was asked before ( Is std::ofstream movable? ) but seems the standard has changed since then ( as detailed in Why can't std::ostream be moved? ) rendering those answers outdated. Certainly, none of those answers explains why the code above does not compile.
当尝试使用 ofstream
的容器时遇到此问题,由于上述原因,它不工作。 / p>
Came across this issue when trying to use containers of ofstream
, which does not work because of the above.
推荐答案
根据标准
27.9.1.11 basic_ofstream构造函数
27.9.1.11 basic_ofstream constructors
或者,它更可读的版本 http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream , std :: basic_ostream<>
有一个移动构造函数,因此代码应该编译。
or, its more "readable" version http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream , std::basic_ostream<>
has a move constructor, so the code should compile.
clang ++ 3.5使用 -std = c ++ 11
或 -std = c ++ 1y
。也gcc5编译它,所以可能它没有实现在libstdc ++ gcc< 5
clang++ 3.5 compiles it with -std=c++11
or -std=c++1y
. Also gcc5 compiles it, so probably it is not implemented in libstdc++ for gcc < 5
有趣的是,缺少move语义在gcc的stdlibc ++实现中没有提及 https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2014
Interestingly, the lack of move semantics is not mentioned on gcc's stdlibc++ implementation https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2014
请参阅 https://gcc.gnu .org / bugzilla / show_bug.cgi?id = 54316 的错误报告,感谢@BoBTFish指出。已确认问题已在gcc5中修复。
See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316 for a bug report, thanks to @BoBTFish for pointing out. It is confirmed that the issue was fixed in gcc5.
这篇关于为什么我不能移动std :: ofstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!