Andres
Andres

Reputation: 1146

Error while deleting a vector pointer to pointers

What do you think about this function?

void deleteVector(vector<Persistent*> *v) {
    if (v) {
        for (int i = 0; i < v->size(); i++)
            delete v[i];
        delete v; 
    }
}

I keep getting the following errors:

I think this is because I'm getting a reference from [] operator... but I don't know how to solve it...

Thank you...

Upvotes: 0

Views: 3155

Answers (2)

David G
David G

Reputation: 96790

v is a pointer, so you'll need to dereference it before using the subscript operator on it:

for (int i = 0; i < v->size(); i++)
    delete (*v)[i];
//         ^^^^

Alternatively, you can use the explicit operator syntax:

delete v->operator[](i);

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

v is the pointer you're passing in. When you do v[i] you are accessing the ith vector. Really, you only have one vector and you want to delete its elements. To do that, dereference the pointer first:

delete (*v)[i];

Upvotes: 0

Related Questions