hiy
hiy

Reputation: 459

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

I have a function that operates on an std::ifstream:

#include <fstream>

void handle(std::ifstream file) {
  // Do things
}

int main() {
  std::ifstream file("x.txt");
  handle(file);
}

This code gives me this error.

However, if I make handle's single parameter a reference (void handle(std::ifstream& file), the code compiles without warnings.

Why?

Upvotes: 0

Views: 23

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

The parameter is passed by value, which requires the argument to be copied.
However, std::ifstream does not provide a copy constructor.

From here:

ifstream (const ifstream&) = delete;

Upvotes: 3

Related Questions