简体   繁体   中英

Returning a vector in C++

I just read this post on SO , that discusses where in memory, STL vectors are stored. According to the accepted answer,

vector<int> temp;

the header info of the vector on the stack but the contents on the heap.

In that case, would the following code be erroneous?

vector<int> some_function() {
  vector<int> some_vector;
  some_vector.push_back(10);
  some_vector.push_back(20);
  return some_vector;
}

Should I have used vector<int> *some_vector = new vector<int> instead? Would the above code result in some code of memory allocation issues? Would this change if I used an instance of a custom class instead of int ?

Your code is precisely fine.

Vectors manage all the memory they allocate for you.

It doesn't matter whether they store all their internal data using dynamic allocations, or hold some metadata as direct members (with automatic storage duration). Any dynamic allocations performed internally will be safely cleaned-up in the vector's destructor, copy constructor, and other similar special functions.

You do not need to do anything as all of that is abstracted away from your code. Your code has no visibility into that mechanism, and dynamically allocating the vector itself will not have any effect on it.

That is the purpose of them!

If you decide for dynamic allocation of the vector, you will have really hard time destroying it correctly even in very simple cases (do not forget about exceptions!). Do avoid dynamic allocation at all costs whenever possible.

In other words, your code is perfectly correct. I would not worry about copying the returned vector in memory. In these simple cases compilers (in release builds) should use return value optimization / RVO ( http://en.wikipedia.org/wiki/Return_value_optimization ) and create some_vector at memory of the returned object. In C++11 you can use move semantics.

But if you really do not trust the compiler using RVO, you can always pass a reference to a vector and fill it in inside the function.

//function definition
void some_function(vector<int> &v) { v.push_back(10); v.push_back(20); }

//function usage
vector<int> vec;
some_function(vec);

And back to dynamic allocation, if you really need to use it, try the pattern called RAII. Or use smart pointers.

It is not important where internally vectors define their data because you return the vector by copy.:) (by value) It is the same as if you would return an integer

int some_function()
{
   int x = 10;
   return x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM