Now I'm going to ask a question about pointers that is probably very simple, even though an hour of searching on google has yielded nothing.
I'm currently working on my Gamepad class, which contains seven pointers of type PadCommand. PadCommand is an abstract base class, so the pointers are meant to be dynamically allocated to one of the base classes.
I'm currently writing the copy constructor for the Gamepad class:
Gamepad(const Gamepad &g){ name = g.name; // Set pointers equal down here}
The problem is, when I set the pointers equal it does a soft copy of the pointer, so the pointers point to the exact memory address of the pointers from the other Gamepad object. The result is, when the other Gamepad object memory is freed, the pointers in this object become garbage, because they were pointing to those addresses.
So basically, how do I make a copy of a dynamically allocated pointer so that the new pointer is the same object without pointing to the same memory address?
Sorry if my explaination sucks, I've been at this for awhile now and am quite tired. Any help would be appreciated.
Ugh, I should've used smart pointers[lol]
Unfortunately I'm zonked out myself due to winter insomnia (stupid winter); so my intellectual output is greatly diminished today. If I gather what you are trying to do correctly you want to make sure that your copies still can access the memory after the original is freed, right?
If so, a common solution is to use reference counting for your pointers. Your Gamepad class can contain a variable to count how many objects have a reference to it. When something new grabs a copy, inrement the counter, when something releases one, decrement it. When the counter reaches zero, destroy the object. That way you'll be sure to only free the object when nothing still has a pointer to it.
I'm pretty sure that boost::shared_ptr works this way, so I'd use that if you can. But it's not too hard to put in the counter yourself if you'd prefer to do it that way.