0

I want to get data from a stream that my function returned, but it throws an exception when I try to. Here is my code in short form:

#include <iostream>
#include <fstream>  
using namespace std;
ifstream& detect() {
    ifstream stream;
    stream.open("in.txt");
    return stream;
}
int main() {
    int s;
    ifstream& fin = detect();
    fin >> s; //exception thrown: Access violation reading
    cout << s;
}

How can I solve this problem? Is it caused because of the reference type of the "fin"?

  • 3
    `stream` is a local variable, so the reference to it is dangling when you return. Using the stream at that point is UB. – cigien Apr 23 '21 at 17:49
  • [If you ask politely](https://godbolt.org/z/nccn8GrPn) the compiler can warn you about trivial mistakes like this. – user4581301 Apr 23 '21 at 17:53
  • 1
    @fabian Using `std::move()` like that will prevent RVO/copy elision from happening: https://stackoverflow.com/questions/17473753/ – Remy Lebeau Apr 23 '21 at 17:59

1 Answers1

1

stream in detect() function is a local variable and will be freed after the function call. You cannot pass a dangling reference of stream. Instead change the code to this:

ifstream detect() {
    ifstream stream;
    stream.open("in.txt");
    return stream;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770