Pranit Kothari Pranit Kothari - 1 year ago 66
C++ Question

Why it is OK to return vector from function?

Please consider this code, I have seen this type of code several times,

is local vector, how it is possible to return from 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::vector<string> words;//this vector will be returned
std::string token;

while (std::getline(file, token, ','))

return words;

Answer Source

Can we guarantee it will not die?

As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

The local variable will go out of scope. after it was moved (or copied).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download