我正在尝试使用文件流实现std::map(实际上是std::pair)。因为标准C++文件流(ifstreams ofstream和fstream)不可复制,所以选择了来自stdio的FILE。
这是最简单的类包装:
#include <stdio.h>
class FileWriter
{
public:
FileWriter(const char* fileName)
{
_fs = fopen(fileName, "w");
}
~FileWriter()
{
fclose(_fs);
}
private:
FILE* _fs;
};
让我们尝试将这个类作为模板参数用于std::map中:
int main()
{
std::map<int, FileWriter> a{ { 1, FileWriter("fl.fl") } };
}
代码编译没有问题,但在运行时出现了内存转储的错误。调试器显示析构函数~FileWriter()执行了两次。为什么会这样,并且如何避免这个错误?
m[10].swap(mystream)
。 - Kerrek SB