在使用ifstream时使用已删除的功能

时间:2017-06-26 09:38:45

标签: c++

我正在尝试打开一个文件并将其处理程序保存在结构中,然后将结构插入到地图中。这是我写的一个简单的代码片段。我收到use of deleted function编译错误。这是因为ifstream类型的fileHandle无法复制,所以整个结构都无法复制?我该如何解决这个问题?

typedef struct speedEntry
{
    std::ifstream fileHandle;
} speedEntry_t;

std::map<uint32_t, speedEntry_t> allSpeed;

speedEntry_t entry = {};

entry.fileHandle.open("path_to_file", std::ifstream::in);
if(!entry.fileHandle.is_open())
    throw an error here;

allSpeed.insert(std::make_pair(1, entry));

2 个答案:

答案 0 :(得分:2)

ifstream不可复制,您的代码正在尝试将它们复制插入allSpeed地图,将插入的代码行更改为此

allSpeed.insert(std::make_pair(1, std::move(entry)));

即。将entry对象移动到地图

答案 1 :(得分:1)

是的,这正是原因,因为using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int outcome = 1; int removed; List<int> list = new List<int>(new int[] { 1, 2, 6, 4, 6, 4, 9, 8, 3, 1 }); for (int j = 0; j < 9; j++) { removed=list[j] ; list.RemoveAt(j); for (int i = 0; i < 9; i++) { outcome *= list[i]; } list.Add(removed); Console.WriteLine(outcome); } Console.ReadKey(); } } } 的{​​{1}}的复制构造函数是here

  

basic_ifstream(const basic_ifstream&amp; rhs)= delete;

删除。

但是,移动构造函数不是,因此您可以明确指定要移动左值,但之后不能重用ifstream

entry