Search code examples
c++memory-managementscopenew-operatordelete-operator

Create new struct, insert into list, re-use pointer, return in vector... whether and how to delete?


In C++ code that I wrote to demonstrate an algorithm in an answer, I'm creating structs in a function using new, storing them in a list, moving them to a vector, then returning the vector:

struct my_struct {int a, b, c;};

std::vector<my_struct> myFunction(...) {
    std::list<my_struct> my_list;
    std::list<my_struct>::iterator current = my_list.begin();
    std::vector<my_struct> my_vector;
    my_struct *new_struct = nullptr;

    while (...) {
        ...
        if (!new_struct) {
            new_struct = new my_struct;
            new_struct->a = ...
        }
        ...
        if (new_struct) {
            new_struct->b = ...
            my_list.insert(current, *my_struct);
            my_struct = nullptr;
        }
        ...
        if (...) {
            current->c = ...
            my_vector.push_back(*current);
            current = my_list.erase(current);
        }
        ...
    }
    return my_vector;
}

It compiles and seems to work correctly, however I'm more used to JavaScript and this code just feels like translated JavaScript; I'm specifically wondering whether I'm creating memory leaks, and whether I have to delete the structs in the calling function (and how).


Solution

  • As others in the question section have already pointed out, you probably shouldn't use new at all. The only reason to use pointers there at all is the if(newstruct) checks, if they are an essential part of your algorithm.

    But if you use new, you should delete, too. It's safe to do that after inserting the struct into the list or vector - the list and vector contain copies.