"Handling map of files in c++ "说不,应该使用 std::map<std::string, std::ofstream*>
,但这会导致new
和delete
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/