Inegregor
Inegregor

Reputation: 1

Why can't I read from a reference on stream returned by function?

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"?

Upvotes: 0

Views: 78

Answers (1)

Ishara Priyadarshana
Ishara Priyadarshana

Reputation: 88

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;
}

Upvotes: 1

Related Questions