I'm trying to make a copy constructor for the following class, but since I got a pointer vector of pointers (I know it sounds silly =p) I don't know if it's enough to just copy the vector itself or do I have to loop through all variables contained in the vector and copy them?
Each vector contains one pointer. Those pointers hold same address. The address of foo. Of course they do; the pointer in gaz is a copy of the pointer in bar.
However, that copy construction did not create a new object as copy of foo, nor update the pointer in gaz to point to such object. In your program a destructor of each would attempt to delete the one and only pointed to object.
In other words, if you do want to make deep copies, then you have to make those copies.
PS. It is late hour, but your destructor looks extremely fishy. In fact, I do bet that it will crash in awesome ways.
So I have to copy every element in order to assure that the copy constructor doesn't make any shallow copies.
Also, what's wrong with the destructor? Don't I get rid of all dangling pointers this way? Changed it from a pointer to a vector to a simple vector of pointers, it's better this way?
1 2 3 4 5 6 7 8 9 10 11 12 13
hand::~hand()
{
std::vector<card*>::const_iterator *it;
for (it = &cards.begin(); it != &cards.end(); ++it)
{
delete it;
it = NULL;
}
cards.clear();
};
You don't need a pointer to the vector. If you want to copy hand you need a copy constructor and operator (operator=const hand & aHand);). If you don't want the copy make it private.
I bet you don't need a pointer to card either. If you don't have pointers copy is no problem at all.
The delete in the destructor is wrong:
1 2 3 4 5 6 7 8 9 10 11 12 13
hand::~hand()
{
std::vector<card*>::const_iterator it; // Not a pointer
for (it = cards.begin(); it != cards.end(); ++it)
{
delete (*it); // Note: (*it) you don't want to delete the iterator but its content
it = NULL; // Unnecessary
}
cards.clear();
}
You should try to avoid pointers as often as possible(especially raw pointers).
I don't know what you're working on but since you asked it's better for you to just have a vector of objects, not pointer to objects.