Lately, I got a little confused about the memory allocation of (de) std::vectors
Suppose I got a normal integer vector: std::vector<int> intv; When I push_back some int , it grows in time. And when I leave the scope (i.e.) of the Function, it is freed up without the need for additional calls.
Great. Take another example:
struct foo_t{ std::string bar: unsigned int derp; } void hurr(){ std::vector<foo_t> foov; foo_t foo; foo.bar = "Sup?"; foo.derp = 1337; foov.push_back(foo); }
Good. When I call hurr() , the vector is created, the foo_t instance is foo_t , the instance is populated and foo_t into the vector. So when I leave the function, the vector is freed and the content (here is one foo_t ) is also freed?
The following example:
struct foo_t{ std::string bar: unsigned int derp; } std::vector<foo_t> hurr(){ std::vector<foo_t> foov; foo_t foo; foo.bar = "Sup?"; foo.derp = 1337; foov.push_back(foo); return foov; }
In my understanding, a vector and its contents live on a stack that receives (eventually) time-rewritten and the vector that I returned, and its contents will be useless. Or does it really return a copy of the vector with a copy of its contents (this requires an instance of Copy-Constructor, if it's not a POD)?
And something obvious:
struct foo_t{ std::string bar: unsigned int derp; } std::vector<foo_t*> hurr(){ std::vector<foo_t*> foov; foo_t foo = new foo_t; foo->bar = "Sup?"; foo->derp = 1337; foov.push_back(foo); return foov; }
Now I need to manually iterate over the vector, delete its contents, and then I can safely allow the vector to fall out of scope, right?
source share