vendredi 27 mai 2016

Delete member of struct on heap after std::move()

I'm currently refactoring and change existing code to C++11 and I wonder if have memory leak. My code has a struct with a std::vector in it as well as a method to shrink() this vector down to its negative elements.

struct mystruct_t {

    int other_stuff;

    std::vector <int> loc;

    // Adds elements to loc vector
    void add(int pos){
        loc.push_back(pos);
    }

    // Shrink the list 
    void shrink () {
        std::vector<int> tmp;
        for (unsigned int i = 0; i < loc.size(); ++i) {
            if (loc[i] < 0) tmp.push_back (loc[i]);
        }
        loc = tmp;
        std::vector<int>(loc).swap (loc);
    }

    mystruct_t(): otherstuff(0) {};
};

In another function I create a new instance of this struct like this:

mystruct_t c = new mystruct_t;
c->add(2);
c->add(3);
...

And later I call the shrink() method of this struct.

c->shrink()

Now I'm not sure what's happening with the "old" loc vector after the shrink function? Will it get destroyed automatically or do I have to destroyed by hand? And if the later, how would I do that?

I also tried to change shrink() to more C++11 style by change it to:

void shrink (){        
    std::vector<int> tmp;
    for (auto &currLoc : loc) {
        if (currLoc < 0) tmp.push_back (currLoc);
    }
    loc = std::move(tmp);
}

But the question remains the same what is happening to the "old" loc vector additionally this seems to increase the memory usage. I'm new to C++11 and not sure if I totally misunderstand the concept?

Aucun commentaire:

Enregistrer un commentaire