When I pass a std::vector<std::string>
by reference to a function which writes to the vector, the called function modifies the vector but the calling function doesn't see the modification.
For example, in the following code, oData
has a size of 20 but data
has size 0. Why?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
bool ReadFile(const std::string & iFile, std::vector<std::string> & oData) {
std::ifstream myfile(iFile);
if (!myfile.is_open()) {
std::cout << "Unable to open file";
return false;
}
else {
std::string line;
while (getline(myfile, line)) {
std::cout << line << '\n';
oData.push_back(line);
}
myfile.close();
}
return true;
}
int main() {
std::vector<std::string> data;
ReadFile("numbers.txt", data);
return 0;
}
Note: Using Visual Studio 2015 on Windows 10
The problem was with the location of the breakpoint in Visual Studio debugger.
Breakpoint after return
--> size of data = 0; screenshot
Breakpoint before return
--> size of data = actual size. screenshot