footy
footy

Reputation: 5941

Using delete operator in a pointer in vector

I have the following vector:

std::vector<xml::Node *> *children;

In my destructor I need to explicitly call delete on the elements pointed to by Node * elements in the children. So I do the following:

std::cout << "xml::Element destructor" << std::endl;
if(children != NULL) {
    if(n_children() > 0) {
        for (int i = 0; i < n_children(); i++) {
            delete children[i];
        }
    }
    delete children;
}

But I get the following error:

oops.cpp: In destructor ‘virtual xml::Element::~Element()’:
oops.cpp:277:42: error: type ‘class std::vector<xml::Node*>’ argument given to ‘delete’, expected pointer

How can I correct this?

Upvotes: 1

Views: 2104

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361732

delete children[i];

should be

delete (*children)[i];

because children is a pointer.

Well, that is the problem with your code at syntactical level, though I feel that there would still be problem at design level even after you fix the above syntax. Why have you declared children as pointer? Why not just this:

std::vector<xml::Node*> children; //non-pointer now

Do you have any solid reason why you didn't opt for this?

Declaring a container as pointer in most cases defies its very purpose as far as memory management is concerned. You use container because you don't want to handle memory-management yourself. Instead you want the container itself to take that burden. The container releases all the resources automatically when it goes out of scope. But if you declare a container as pointer, then you're taking the burden to delete the container. If you miss to do that, then the container will never release the resources which it has acquired, and there will be memory leak.

Upvotes: 3

Related Questions