As a Java developer I have the following C++ question.
If I have objects of type A and I want to store a collection of them in an array,
then should I just store pointers to the objects or is it better to store the object itself?
In my opinion it is better to store pointers because:
1) One can easily remove an object, by setting its pointer to null
2) One saves space.
Pointers or just the objects?
You can’t put references in an array in C++. You can make an array of pointers, but I’d still prefer a container and of actual objects rather than pointers because:
The only times I’d advocate putting pointers (or smart pointers would be better) in a container (or array if you must) is when your object isn’t copy construable and assignable (a requirement for containers, pointers always meet this) or you need them to be polymorphic. E.g.
If you want to go down this road boost pointer containers might be of interest because they do all of the hard work for you.
Removing from arrays or containers.
Assigning
NULLdoesn’t cause there to be any less pointers in your container/array, (it doesn’t handle thedeleteeither), the size remains the same but there are now pointers you can’t legally dereference. This makes the rest of your code more complex in the form of extra if statements and prohibits things like:I really dislike the idea of allowing
NULLs in sequences of pointers in general because you quickly end up burying all the real work in a sequence of conditional statements. The alternative is thatstd::vectorprovides anerasemethod that takes an iterator so you can write:to remove the first or
v2.begin()+1for the second. There’s no easy “erase the nth element” method though onstd::vectorbecause of the time complexity – if you’re doing lots of erasing then there are other containers which might be more appropriate.For an array you can simulate erasing with:
preserving the order requires a series of shuffles instead of a single swap, which nicely illustrates the complexity of erasing that
std::vectorfaces. Of course by doing this you’ve just reinvented a pretty big wheel a whole lot less usefully and flexibly than a standard library container would do for you for free!