0

Say I have a vector of pointers to "Order" objects. Now I want to remove an order from this vector. I wonder if the following is the right way to remove such a pointer?

std::vector<Order*> orders; // somehow I obtained a vector of Order*, and an iterator it that points to // an order that I want to remove completely. // does the following work? Order *order = *it; orders.erase(it); delete order; 
6
  • 4
    That'll work. But you might consider smart pointers or Boost ptr_vector. Commented May 31, 2012 at 15:58
  • Once erase is called will order == NULL? Commented May 31, 2012 at 16:04
  • 1
    Be sure the order object has been created with new and is not shared with other, causing a dangling pointer Commented May 31, 2012 at 16:04
  • @ahenderson no, it cannot affect order value (a pointer). Also delete order does not change order value. It continue pointing to the same area, even if after delete is is an invalid area. Commented May 31, 2012 at 16:06
  • 1
    @Alessandro: Actually, I think delete order; is permitted to set order to a null pointer. At least Bjarne Stroustrup says so in his C++ style/FAQ, that might be out of date and I can't be bothered to check ;-) In practice, I don't think any implementation bothers. Commented May 31, 2012 at 16:10

3 Answers 3

3

Was the pointer the result of new? Has anyone else deleted it first? If "yes" and "no", then your code will delete the object.

Sign up to request clarification or add additional context in comments.

3 Comments

Are there any other copies of the pointer? If "yes", then you've just turned them into lethal deathtraps.
I second Mike Seymour's comment. Also do not forget to set 'order = NULL' or 'order = nullptr' (if you are using C++0x) after you have performed the deletion.
I agree with Mike too, I'm not advocating dynamic allocation, just explaining how delete works. I mostly disagree with setting pointers to null after deleting them. Code that deletes something almost always should in any case be designed so that the pointer goes out of scope pretty much immediately afterwards. In the very rare cases where that's not the case (such as perhaps in the reset function of a smart pointer), sure, setting it to null might indicate "nothing to see here". But as I say, that's rare, and should not be encouraged just for the sake of it.
3

This will delete the order object. So yes this is the correct way.
Nevertheless you should think about the usage of smart pointers like unique_ptr or shared_ptr.

Comments

0

Yes. this is the right way. Containers do not delete their content when it's erased.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.