std::vector<int> fun() { std::vector<int> temp; for(...) { // заполняем "temp" чем-либо } return temp; } std::vector<int> testVec = fun(); 

or

 void fun(std::vector<int>& vec) { for(...) { // заполняем "vec" чем либо } } std::vector<int> testVec; fun(testVec); 

How will it be better, faster and in general - how to return the container correctly?

ps I read a bunch of articles on this topic on the foreign "stack", but there all the topics are old, and I’ve already left with ++ 14 and 2016 in the yard, I would like to hear the advice and opinions of the "experts" on с++ , taking into account the new standards In general, please share your experiences.

  • 2
    Considering that modern compilers support NRVO , and with ++ 11 and later allows you to use the move quintar ... both methods will work approximately equally quickly. - KoVadim
  • 2
    In the second case, it seems, it will not be possible to “fill in” the constant vector. - cridnirk

2 answers 2

Here, the differences are more likely not technical - as quickly (as you have already been answered, almost the same), but semantic ones. For example, if in a function you add some elements to a vector, then in the first version you can only add them to the initially empty vector, and in the second version you can add a non-empty vector.

In a word, do what is more correct from the point of view of program logic :)

    In the context of this issue, in C ++ 14 nothing has changed significantly compared to C ++ 11.

    Use the first option, then either the optimizer will make NRVO (a special case of copy elision ), or the moving constructor will be called, because in return temp; temp expression is considered r-value.
    You can read more in this issue .