Is it possible to handle std::ofstream with std::map?

耗尽温柔 提交于 2019-12-24 01:09:58

问题


"Handling map of files in c++" says no, one shall use std::map<std::string, std::ofstream*>, but this leads to the new and delete actions, which is not so neat.

Since "Is std::ofstream movable? Yes!" and it's possible to "std::map<>::insert using non-copyable objects and uniform initialization", is it possible to handle a collection of ofstream using std::map? so that one won't worry about closing filestreams and delete to release memory.

I can compromise that during using std::map<std::string, std::ofstream>, only create, use (it to write) and close, not to copy it.


回答1:


Yes it is possible. See sample code below.

I can compromise that during using std::map<std::string, std::ofstream>, only create, use (it to write) and close, not to copy it.

They are not copyable, so in your final comment, you are correct, you will be unable to copy it. You can move assign though, if that's what you want to do.

#include <iostream>
#include <fstream>
#include <map>

int main()
{
    std::map<std::string, std::ofstream> map;
    map.emplace("foo", std::ofstream("/tmp/foo"));
    map.emplace("bar", std::ofstream("/tmp/bar"));

    map["foo"] << "test";
    map["foo"].flush();

    std::ifstream ifs("/tmp/foo");
    std::string data;
    ifs >> data;

    std::cout << data << '\n';

    return 0;
}

Output:

test



来源:https://stackoverflow.com/questions/40072678/is-it-possible-to-handle-stdofstream-with-stdmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!