Ian Young
Ian Young

Reputation: 1746

Using std::List with object pointers

I am writing a quad tree which stores pointers to collidable objects in an stl list. I want the quad tree to be able to move the objects from node to node depending on their position in the world, and would like to just get something confirmed:

If I remove the pointer from the list, to insert the object into another tree node (such as the parent tree node), will the destructor for the pointed-to object be called? For clarification, I do not want the object destroyed, as it is used & managed elsewhere in the program.

Thanks, in advance.

Upvotes: 0

Views: 194

Answers (4)

Willem van Doesburg
Willem van Doesburg

Reputation: 534

no, destructors are never called on pointers in STL. It only gets destroyed when you call delete explicitly on the object pointed to (or if the object when stored on the stack goes out of scope) or if you use smart pointers.

Upvotes: 1

Dani Barca Casafont
Dani Barca Casafont

Reputation: 273

I'm not sure if what you say will happen, but anyway it might be a good practise to reset your pointer to NULL before deleting the instance. Also, remember to make the pointed-object to be pointed by the correct node, that probably will be the node that was pointing to the node you erased.

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

The destruction of an object is determined by its storage duration. If an object has automatic storage duration (like a local variable), it will be destroyed when it goes out of scope. If an object is dynamically allocated (using new), it will only be destroyed when you do delete on it. If it has static storage duration, it will be destroyed when the program ends.

If you are just copying the pointer out of one node and into another and as long as the object it points at hasn't been destroyed according to the above rules, the pointer will continue to point at the same valid object.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

The actual object in the list (i.e. the pointer) will be destructed, but not what the pointer points to.

It might be a little confusing to begin with, but if you see the pointer, and what it points to, as completely separate entities it makes a lot more sense.

Upvotes: 3

Related Questions