如果我不使用引用,为什么无法编译此代码?

Why won't this code compile if I don't use a reference?

本文关键字:编译 代码 为什么 引用 如果      更新时间:2023-10-16

我有一个在std::ifstream:上操作的函数

#include <fstream>
void handle(std::ifstream file) {
  // Do things
}
int main() {
  std::ifstream file("x.txt");
  handle(file);
}

这个代码给了我这个错误。

但是,如果我将handle的单个参数作为引用(void handle(std::ifstream& file),则代码编译时不会发出警告。

为什么?

参数是通过值传递的,这需要复制参数
但是std::ifstream不提供复制构造函数。

从这里:

ifstream (const ifstream&) = delete;