std::ofstream 是可移动的吗?
我有这张地图,可以在 MSVC10 中正常编译:
std::map<std::string, std::ofstream> m_logFiles;
但是在启用了 C++0x 的情况下使用 g++ 4.5 的 ubuntu 上,我收到以下错误消息:
/usr/include/c++/4.5/bits/ios_base.h|785|error: ' std::ios_base::ios_base(const std::ios_base&)' 是私有的
通过使用指针而不是对象,我解决了问题。
在网上搜索,我了解到流不应该被复制(原因已经得到很好的解释)。但我的问题是, std::ofstream 是可移动类型吗?如果是,是否应该允许其在标准容器中用作模板参数?
如果是,那么 g++ 在这一点上落后于 MSVC10 吗? (这可以解释为什么它适用于 MSVC)。我知道要求编译器编写者完全实现甚至不是最终版本的东西是愚蠢的,但我对未来很好奇。
使用 g++ 4.6.1 没有帮助。
编辑:阅读评论我进一步挖掘,发现插入导致了问题,而不是地图的声明。
阅读 Cubbi 的链接我尝试了以下操作:
#include <string>
#include <fstream>
#include <map>
using namespace std;
int main()
{
map<string, ofstream> m_logFiles;
ofstream st;
m_logFiles.insert(make_pair<string, ofstream>(string("a"), move(st)));
return 0;
}
但仍然没有运气。 g++ 抱怨使用 b 删除的复制构造函数。
I have this map which compiles fine in MSVC10 :
std::map<std::string, std::ofstream> m_logFiles;
But on ubuntu using g++ 4.5 with C++0x enabled, I get the following error message :
/usr/include/c++/4.5/bits/ios_base.h|785|error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private
By using pointers instead of objects, I resolved the problem.
Searching on the web, I learned that streams are not meant to be copied (the why was well explained). But my question is, is std::ofstream a movable type ? If it is, shouldn't it allow its use as a template parameter in the standard containers ?
If yes, then is g++ behind MSVC10 on this point ? (which would explain why it works on MSVC). I know it would be silly to ask compiler writers to fully implement something that isn't even final, but I'm curious regarding the future.
Using g++ 4.6.1 didn't help.
Edit : reading the comments I dug a little bit further and found that the insert is causing the problem, not the declaration of the map.
Reading Cubbi's link I tried the following :
#include <string>
#include <fstream>
#include <map>
using namespace std;
int main()
{
map<string, ofstream> m_logFiles;
ofstream st;
m_logFiles.insert(make_pair<string, ofstream>(string("a"), move(st)));
return 0;
}
But still no luck. g++ complains about the use of b deleted copy constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::ofstream
是可移动的。该程序使用 clang/libc++ 为我编译:参考 27.9.1.11 [ofstream.cons]。
std::ofstream
is movable. This program compiles for me using clang/libc++:Reference 27.9.1.11 [ofstream.cons].
我之前问过类似的问题,后来发现GCC似乎还不支持可移动的fstreams(我刚刚测试了GCC 4.6.1),详见 这个答案。
I asked a similar question earlier, and later found that GCC doesn't seem to support movable fstreams yet (I just tested GCC 4.6.1) as detailed in this answer.