有一个类似的问题,但没有得到回答。
我正在尝试创建一个std::ofstream对象的映射,但我无法构建代码。
到目前为止我已经试过了
//std::map<std::string, std::ofstream> my_files; //this fails
std::map<std::string, std::ofstream& > my_files;
for(auto & member: members){
filename=GetFileName();
//create the file
std::ofstream thefile(filename);
my_files[member.first]=thefile;
}
//Here I use the ofstreams in the map to write etc我尝试了第一个(注释)行,我得到了this error。使用已删除的功能。因此,我将其更改为上面的行,但仍然会出现相同的错误:使用已删除的函数‘std::basic_ofstream<
如何构建流对象的映射?
注意:在类似的问题中,有人建议使用字符串映射,但使用流映射的原因是,每次我想对每个字符串进行最小的更改时,我都不会打开和关闭文件。
发布于 2021-12-23 06:27:52
问题是引用本身不是对象。引用将引用到其他对象。因此,不能将引用存储在容器中。
您可以通过将 my_files[member.first]=thefile;替换为:
my_files.emplace(member.first, std::ofstream(filename));此外,将 std::map<std::string, std::ofstream& > my_files;替换为:
std::map<std::string, std::ofstream > my_files; //removed the &修正码
std::map<std::string, std::ofstream > my_files; //removed the &
for(auto & member: members){
filename=GetFileName();
my_files.emplace(member.first, std::ofstream(filename)); //ADDED THIS
}发布于 2021-12-23 06:28:03
首先,引用不能存储在容器中。但是,您似乎希望存储std::ofstream本身,而不是对它的引用,因为否则您的std::ofstream对象将在循环体的末尾被销毁,从而在地图中留下一个悬空引用,因此:
std::map<std::string, std::ofstream > my_files;其次,流对象(如std::ofstream )是不可复制的,因此不能简单地将它们复制到映射中。
但是,它们是可移动的,因此您可以将它们移动到地图中:
my_files[member.first] = std::move(thefile);(需要#include<utility>)或者通过直接在赋值中构造它:
my_files[member.first] = std::ofstream(filename);有关std::move的解释,如果您以前没有见过它,请参见this question。
https://stackoverflow.com/questions/70458360
复制相似问题