I have the code:
std::list<Node *> lst;
//....
Node * node = /* get from somewhere pointer on my node */;
lst.remove(node);
Does the std::list::remove method call the destructor (and free memory) of each removed element? If so, how I can avoid it?
Yes, removing a
Foo*from a container destroys theFoo*, but it will not release theFoo. Destroying a raw pointer is always a no-op. It cannot be any other way! Let me give you several reasons why.Storage class
Deleting a pointer only makes sense if the pointee was actually allocated dynamically, but how could the runtime possibly know whether that is the case when the pointer variable is destroyed? Pointers can also point to static and automatic variables, and deleting one of those yields undefined behavior.
Dangling pointers
There is no way to figure out whether the pointee has already been released in the past. Deleting the same pointer twice yields undefined behavior. (It becomes a dangling pointer after the first delete.)
Uninitialized pointers
It is also impossible to detect whether a pointer variable has been initialized at all. Guess what happens when you try to delete such a pointer? Once again, the answer is undefined behavior.
Dynamic arrays
The type system does not distinguish between a pointer to a single object (
Foo*) and a pointer to the first element of an array of objects (alsoFoo*). When a pointer variable is destroyed, the runtime cannot possibly figure out whether to release the pointee viadeleteor viadelete[]. Releasing via the wrong form invokes undefined behavior.Summary
Since the runtime cannot do anything sensible with the pointee, destroying a pointer variable is always a no-op. Doing nothing is definitely better than causing undefined behavior due to an uninformed guess 🙂
Advice
Instead of raw pointers, consider using smart pointers as the value type of your container, because they take responsibility for releasing the pointee when it is no longer needed. Depending on your need, use
std::shared_ptr<Foo>orstd::unique_ptr<Foo>. If your compiler does not support C++0x yet, useboost::shared_ptr<Foo>.Never, I repeat, NEVER EVER use
std::auto_ptr<Foo>as the value type of a container.