Should I store entire objects, or pointers to objects in containers?

Stéphane picture Stéphane · Sep 26, 2008 · Viewed 63.9k times · Source

Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.

Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to those objects in my STL containers?

I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible.

Two very obvious disadvantage to playing with pointers: 1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL. 2) I cannot create a temp object on the stack and add it to my containers.

Is there anything else I'm missing?

Answer

Torbjörn Gyllebring picture Torbjörn Gyllebring · Sep 26, 2008

Since people are chiming in on the efficency of using pointers.

If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference.

Otoh, if updates are common storing pointers will save the copy/relocation costs.