0

Nothing is stored in moviesToRead after stepping through the readMovies() function, however it seems the vector in the function stores everything the way I need it to.

int main() {

    
    vector <string>& moviesToRead = readMovies();

    int size = moviesToRead.size();

    for (int i = 0; i < size; i++) {
        cout << moviesToRead[i] << endl;
    }
    

}//main

When I step through the function, everything I need to be in it is.

vector<string> &readMovies(){

    ifstream fin;
    ofstream fout;
    string movieName;
    int size = 0;
    
    vector<string> movieVector;

    cout << ENTER_MSG[0] << endl;

    string fileName;

    cin >> fileName;

    fin.open(fileName);

    while (getline(fin, movieName)) {

        movieVector.push_back(movieName);


    }//while file exists

    return movieVector;

}//read movies from file
  • 1
    Thou shalt not return a local variable by reference. `movieVector` goes out of scope at the end of the function before the caller can make use of the reference. Instead, return it by value and trust the compiler to optimize. – user4581301 Jul 01 '22 at 21:43
  • I'm 95% confident that you're ignoring a very nice compiler warning along the lines of, "Returning a reference to a local variable." Warnings are good. You should read them. – 3Dave Jul 01 '22 at 22:10

2 Answers2

0

You can't pass a reference to a local (ASDV) variable, as it's out of scope and is destructed right after you return. Your code has UB. We return reference when e.g. an object encapsulates it or when it's a static, but not when it's locally constructed.

lorro
  • 10,687
  • 23
  • 36
0

Change the return type of your function to:

vector<string> readMovies()

(removing the reference). Otherwise, you are returning a reference to an object that has been destroyed, and you will get undefined behavior.

user3188445
  • 4,062
  • 16
  • 26
  • 1
    @3Dave no it doesn't, because of NRVO. https://en.cppreference.com/w/cpp/language/copy_elision – user3188445 Jul 01 '22 at 22:22
  • @3Dave But rvalue references are also since C++11, so your suggestion to use `&&` isn't super useful. Most compilers implement C++11 or later, and even if you are compiling in a C++98 mode, there's no reason for them to disable NRVO. Returning a vector is the right answer for this problem. – user3188445 Jul 01 '22 at 22:37
  • You're correct. There's a reason I deleted that comment. :) Good call. – 3Dave Jul 01 '22 at 22:37