Please consider this code. I have seen this type of code several times. words
is a local vector. How is it possible to return it from a function?
Can we guarantee it will not die?
std::vector<std::string> read_file(const std::string& path)
{
std::ifstream file("E:\\names.txt");
if (!file.is_open())
{
std::cerr << "Unable to open file" << "\n";
std::exit(-1);
}
std::vector<string> words;//this vector will be returned
std::string token;
while (std::getline(file, token, ','))
{
words.push_back(token);
}
return words;
}
The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.
See this question & answer for further details.
The function will move the value. See this answer for further details.