简体   繁体   中英

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:

  • test.cpp: In member function 'void Koala::ListAddressAction::deleteVector(std::vector >*)':

  • test.cpp:160: error: type 'class std::vector >' argument given to 'delete', expected pointer test.cpp: In member function 'virtual void Koala::ListAddressAction::execute()':

  • test.cpp:176: error: no matching function for call to 'Koala::ListAddressAction::deleteVector(std::vector >*&)'

  • test.cpp:157: note: candidates are: void Koala::ListAddressAction::deleteVector(std::vector >*)

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

Thank you...

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);

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

delete (*v)[i];

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