c++11 - 是否可以使用 std::map 处理 std::ofstream ?

标签 c++11 stdmap

"Handling map of files in c++ "说不,应该使用 std::map<std::string, std::ofstream*> ,但这会导致newdelete Action ,不是那么整齐。

因为“Is std::ofstream movable?是的!”并且可以“std::map<>::insert using non-copyable objects and uniform initialization”,是否可以处理ofstream的集合使用std::map ?这样就不用担心关闭文件流和 delete释放内存。

我可以在使用std::map<std::string, std::ofstream>期间妥协,只创建、使用(写)和关闭,不复制。

最佳答案

是的,这是可能的。请参阅下面的示例代码。

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

它们不可复制,因此在您的最终评论中,您是正确的,您将无法复制它。不过,如果您愿意的话,可以移动分配。

#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;
}

输出:

test

关于c++11 - 是否可以使用 std::map 处理 std::ofstream ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072678/

相关文章:

c++ - 基类中删除的构造函数是否影响子类?

c++ - 添加 unique_ptr 作为类的实例字段,而不是显式删除复制/赋值构造函数

c++ - 当其键不存在时初始化 std::map 值

c++ - 使用值为 std::shared_ptr 的映射是否是具有多索引类列表的良好设计选择?

c++ - O(log n) 索引更新和搜索

c++ - 创建一个类来访问和指定 vector 类型,并构建一个获取位置并为其分配区域的类

c++ - 设计一个只能由特定类实例化的类(如果可能,通过 make_unique)

c++ - 如何使用 std::is_volatile?

c++ - tellp() 是否未在追加模式下定义?

c++ - std::map 如何确保所有指针都为空?