Re: Which is best way to store objects?
On Jan 1, 6:56 pm, Angus <anguscom...@gmail.com> wrote:
I want to store a collection of objects in a vector. I think
the best way is for me to create each object on the free store
(heap) and then store a pointer to the object in the vector.
What are the semantics of the object? If they're value, then
you shouldn't allocate on the heap, but rather copy. (And if
they aren't value, your collection is logically a collection of
pointers to the object, so it doesn't matter.)
Eg like this:
std::vector<MyWidget*> m_widgets;
MyWidget* newone = new MyWidget;
//populate/process
m_widgets.push_back(newone);
Rather than:
std::vector<MyWidget> m_widgets;
MyWidget newone;
//populate/process
m_widgets.push_back(newone);
Reason being that with a pointer the push back does not have
to do a copy of the entire object, it simply copies the
address of the object.
Big deal. If the profilers shows this to be a bottle neck, you
can consider using pointers. (Normally, I'd look to making
copying faster first, but it's not always that simple.) But
otherwise, all you're doing is creating confusion.
The only downside to pointer approach is having to delete the
object at the end but that is easy enough to do.
There's no real downside nor upside. A container of pointers
has radically different semantics than a container of the
objects themselves, and you can't simply substitute one for the
other. If your object has value semantics, a container of
pointers to it is an error, and doesn't work without a lot of
hassle on the user side. If your object has entity semantics,
then you can't put it in a container (since it cannot be copied,
at least not externally); any containers will use pointers.
(BTW: if your Widget refers to a graphic Widget, it probably has
identity, and can't be copied or put into a container.)
--
James Kanze