Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::ofstream movable?

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.

like image 787
Jonathan Merlet Avatar asked Aug 15 '11 15:08

Jonathan Merlet


2 Answers

std::ofstream is movable. This program compiles for me using clang/libc++:

#include <string>
#include <fstream>
#include <map>

int main()
{
    std::map<std::string, std::ofstream> m_logFiles;
}

Reference 27.9.1.11 [ofstream.cons].

like image 87
Howard Hinnant Avatar answered Sep 23 '22 03:09

Howard Hinnant


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.

like image 45
Clinton Avatar answered Sep 23 '22 03:09

Clinton