Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it OK to return a 'vector' from a function?

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; } 
like image 957
Pranit Kothari Avatar asked Mar 26 '14 08:03

Pranit Kothari


1 Answers

Pre C++11:

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.

C++11:

The function will move the value. See this answer for further details.

like image 176
Tim Meyer Avatar answered Sep 24 '22 04:09

Tim Meyer