简体   繁体   中英

How to free a pointer to a vector storing pointers to a struct

struct node {
    std::vector<struct node*> * list;
}

int main() {
   struct node * n = new struct node;
   n->list = new std::vector<struct node*>();
   n->list->push_back(n);
   return 0;
}

How can I delete the n->list with freeing all the pointers that the list is storing?

Will it be n->list->clear()? Or do I have to traverse n->list and call delete or free operator on each element in the list.

std::vector does not assume ownership of dynamically created objects.
(Even if it wanted to, or you created a specialisation or your own implementation, it's impossible to distinguish dynamic allocations from other pointers.)
You need to traverse the vector and free the elements.

The safer/simpler would be

struct node {
    std::vector<node> list;
};

int main() {
   node n;
   n.list.resize(1);
}

or if you need pointer:

struct node {
    std::vector<std::unique_ptr<node>> list;
};

int main() {
   node n;
   n.list.push_back(std::make_unique<node>());
}

First of all: you don't need so much pointers.

If you want it be be this way, you should delete it exactly the same way you have ' new ed' it :).

In your example:

int main() {
   struct node * n = new struct node;
   n->list = new std::vector<struct node*>();
   n->list->push_back(n);
   delete n->list;             // here's the change
   delete n;                   // another required delete
   return 0;
}

But as I said, too much new s. You can write your struct node as:

struct node {
    std::vector<struct node*>  list;
}

it will cause the list to be automatically deleted when node object is being deleted.

This line: struct node * n = new struct node; also can be converted into: node n;

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