class A{};
list<A> Alist;
A *ap=new A;
Alist.insert(*ap);
...
list<A>::iterator it;
...// now 'it' point to the element created by new as above
Alist.erase(it); // Destructor of A is called, what about the memory allocated?
delete ap;//Is this necessary?
A simpler question: if we add one item in the vector or list, do we copy or direct link it to the vector or list? My understanding is copy, confusing...
In STL, vector and list both have erase() and pop() functions to remove some item from the vector or list. What if the item is created through "new" as described above? Can anyone explain it to me? Thanks a lot.
erase simply removes the item from the list. If the item was allocated with new, this does not delete it.
However your example has a separate problem. You are putting a copy of the A in the list.
1 2 3 4 5 6 7 8 9 10
list<A> Alist;
A *ap=new A; // creates a new A
Alist.insert(*ap); // copies that A to another A
// NOTE: this does not put 'ap' in the list! It creates a separate A and copies it
// into the list
list<A>::iterator it = /* ... */;
Alist.erase(it); // This destroys the copy, but 'ap' remains unchanged
delete ap; // so yes, this is necessary
list<A*> Aplist;
A *ap=new A;
Aplist.insert(ap);
...
Aplist.erase(it); // This time what would happen? My understanding: item in Aplist
// is of course a pointer copy, and remove it also leave the new
// allocated memory untouched,right?
delete ap; // so we still can do this?