Search code examples
c++vectorstldelete-operator

Deleting a element from a vector of pointers in C++


I remember hearing that the following code is not C++ compliant and was hoping someone with much more C++ legalese than me would be able to confirm or deny it.

std::vector<int*> intList;
intList.push_back(new int(2));
intList.push_back(new int(10));
intList.push_back(new int(17));

for(std::vector<int*>::iterator i = intList.begin(); i != intList.end(); ++i) {
  delete *i;
}
intList.clear()

The rationale was that it is illegal for a vector to contain pointers to invalid memory. Now obviously my example will compile and it will even work on all compilers I know of, but is it standard compliant C++ or am I supposed to do the following, which I was told is in fact the standard compliant approach:

while(!intList.empty()) {
  int* element = intList.back();
  intList.pop_back();
  delete element;
}

Solution

  • Your code is fine. If you're worried for some reason about the elements being invalid momentarily, then change the body of the loop to

    int* tmp = 0;
    swap (tmp, *i);
    delete tmp;