mardi 1 novembre 2016

Questions on memorybehavior of vectors

I got a bit confused lately about the memory (de)allocation of std::vectors

Lets assume I got normal vector of integer: std::vector<int> intv; When I push_back some int's it grows by time. And when I leave the scope (i.e.) of the function, it gets deallocated without the need of extra calls.

Great. Lets have 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);
}

Okay. When I call hurr() the vector gets created, a foo_t instance gets created, the instance gets filled and pushed to the vector. So when I leave the function, the vector gets deallocated and the content (here one foo_t) gets deallocated, too?

Next 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, the vector and its contents live in the stack, which gets (eventually) overwritten by time and the vector I have returned and its contents will be useless. Or does it actually returns a copy of the vector with a copy of its contents (requires a Copy-Constructor for the contentdatatype if its 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 have to manually itterate over the vector, delete its contents and then I can safely let the vector fall out of scope, right?

Aucun commentaire:

Enregistrer un commentaire