I would like to add 2 elements to a vector<Node*> and then clear all the elements and release the memory.
Does this code do that in a right way?
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int value;
// ...and some other fields and methods...
};
int main(int argc, char** argv) {
Node* n = new Node;
n->value = 20;
vector<Node*> v;
v.push_back(n);
n = new Node;
n->value = 52;
v.push_back(n);
for (vector<Node*>::iterator i = v.begin(); i != v.end(); i++) {
cout << (*i)->value << endl;
delete *i;
*i = NULL;
}
v.clear();
return (EXIT_SUCCESS);
}
It looks fine to me. There are a few things that I’d change (subjectively):
Then I’d avoid reusing
n(actually, I’d avoid it entirely):Also, you may want to consider smart pointers to track your memory for you. See shared_ptr and ptr_vector.