If I have a definition in a class header such as this:
vector<baddie*> baddies;
which I then initialise in the constructor like this:
Class::Class(vector<baddie*> input)
{
baddies = input;
}
What do I end up with? Two vectors with two sets of pointers pointing to the objects?
Would it be better to simply point to the original vector? Is this even possible?
Or would it be better to hold a vector of pointer references in the class so as to not duplicate pointers? What is the best practice for accessing objects and arrays of objects in multiple classes? References? Pointers? Pointer references? Thank you in advance!
It depends on the semantics that you want to provide. In C++11 what you would probably want to do is something like:
Which will move the memory from the copy in the argument to the member, while in C++03 you would probably write:
Which will initialize the vector with a copy.
Note that this discussion only relates to the vector contents, not to the data pointed by those
baddiepointers. That is, in both cases, there will be two vectors with pointers to refer to the same elements (i.e. only one copy of eachbaddiein memory, with two pointers referring to it).Depending on the semantics of your application, you might want to go from this intermediate shallow copying to either end: Perform a deep copy (i.e. create new
baddieelements in memory, so that the original and the copy are fully unrelated once the constructor completes) or avoid coping at all, and just store a reference/pointer so that both vectors are exactly the same (insertion inside or outside of the class will be visible outside/inside the class).Also, beware of vector of pointers, you need to manage the memory manually before the vector is destructed.