在c ++中处理文件映射说不,应该使用 std :: map< std :: string,std :: ofstream *> ,但这会导致 new 和 delete 操作,这并不是那么整齐。
"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.
由于 std :: ofstream是否可移动?是的!并且可以使用以下方法 std :: map<> :: insert不可复制对象和统一初始化,是否可以使用 std :: map $ c处理 ofstream 的集合$ c>?这样一来,您就不必担心关闭文件流和删除来释放内存了。
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.
我可以在使用过程中妥协这一点 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.
推荐答案是的。参见下面的示例代码。
Yes it is possible. See sample code below.
我可以在使用 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.
它们不可复制,因此在您的最终评论中,您是正确的,将无法复制它。
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; }输出:
test
test
更多推荐
是否可以使用std :: map处理std :: ofstream?
发布评论