Hi there. I am having some trouble trying to figure out how to delete a pointer that is held in a vector.

int main()
    vector<Test*> iVector1;
    vector<Test*> iVector2;

    vector<Test*>* pVec1(&iVector1);
    vector<Test*>* pVec2(&iVector2);

    pVec1->push_back(new Test(11));
    pVec1->push_back(new Test(12));
    pVec2->push_back(new Test(23));
    pVec2->push_back(new Test(24));

    //delete iVector1.at(0);
    delete iVector1[0];
    iVector1.at(0) = new Test(21);
    pVec1->at(1) = new Test(22);

neither of the delete lines i have tried work. Both result in a link1120 error.

The purpose of this program is to test various vector functionality, so i know what to do when i apply it to a larger program i am working on. that is why there are both Vectors and Vector pointers.

Any help is much appriciated. (let me know if you need more information)

The correct ending for your main function is this:

  delete iVector1[0];
  iVector1.at(0) = new Test(21);
  delete pVec1->at(1);
  pVec1->at(1) = new Test(22);

  for(int i = 0; i < iVector1.size(); ++i)
    delete iVector1[i];
  for(int i = 0; i < iVector2.size(); ++i)
    delete iVector2[i];

As for the linking error, this is not an error in the code, but an error in the linking. Did you define the destructor of your Test class in a cpp file? If you did, you must compile both cpp files together (the cpp file with the main function and the one with the implementations of the functions of the Test class). The linking error simply means that the compiler cannot find the definition (implementation) of the destructor of the Test class.

Ahh thank you very much, it took me a while but i figured out that even though there is nothing in the destructor for the test class i still have to write it, rather than just declare it, which is what was causing all the problems.


This question has already been answered. Start a new discussion instead.