是否可以用 std::map 处理 std::ofstream?
Is it possible to handle std::ofstream with std::map?
"Handling map of files in c++" 说不,应该使用 std::map<std::string, std::ofstream*>
,但这会导致 new
和 delete
操作,这不是那么整洁。
自“Is std::ofstream movable? Yes!" and it's possible to "std::map<>::insert using non-copyable objects and uniform initialization”以来,是否可以使用 std::map
处理 ofstream
的集合?这样就不用担心关闭文件流和 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
"Handling map of files in c++" 说不,应该使用 std::map<std::string, std::ofstream*>
,但这会导致 new
和 delete
操作,这不是那么整洁。
自“Is std::ofstream movable? Yes!" and it's possible to "std::map<>::insert using non-copyable objects and uniform initialization”以来,是否可以使用 std::map
处理 ofstream
的集合?这样就不用担心关闭文件流和 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