Insert File stream to std::map

Viewed 1363

I'm trying to implement std::map (actually std::pair) with file streams. Because standart c++ file streams (ifstreams ofstream, and fstream) aren't copyable, choice fell on the FILE from stdio. This is simplest class wrapper:

#include <stdio.h>
class FileWriter
{
public:
    FileWriter(const char* fileName)  
    {
        _fs = fopen(fileName, "w");
    }
    ~FileWriter() 
    { 
        fclose(_fs); 
    }

private:
    FILE* _fs;
};

Let's trying to use this class as template parameter in std::map:

int main()
{
    std::map<int, FileWriter> a{ { 1, FileWriter("fl.fl") } };
}

It compiles well, but I get a runtime error - memory dump. Debugger shows, that the destructor ~FileWriter() performed twice. Why this happened and how to avoid this error?

4 Answers
Related