So you would go for the second or third example presented in my original post?Originally Posted by Bubba
So you would go for the second or third example presented in my original post?Originally Posted by Bubba
Parts of my days are spent bug fixing...err. I’m sorry...I’ve just been reminded that we don’t have bugs. We have undocumented features. (Jonathan Ackley on Monkey Island 3)
I have a follow-up question regarding this:Originally Posted by Daved
How do you make, say, a vector handle memory management if you are allocating your objects on the heap which you would probably do to avoid copying your objects everytime the vector is expanded?
Parts of my days are spent bug fixing...err. I’m sorry...I’ve just been reminded that we don’t have bugs. We have undocumented features. (Jonathan Ackley on Monkey Island 3)
If you are storing pointers in your vector (usually because your classes are expensive to copy or because you are using polymorphism), then you cannot make vector manage that memory.
Instead, you use shared_ptr to manage the memory of the objects while vector manages the array memory that holds the pointers. Another option is to use a ptr_vector. Both shared_ptr and ptr_vector are in boost. The ptr_vector class is probably a better fit than a vector of shared_ptr's, but the shared_ptr is almost standard and will be part of the next standard, so if you start using it now it is more likely to always be available in the future.
In the case of shared_ptr, you still call new yourself, but the effect is the same because it will clean up automatically and any out of memory exceptions will propagate out of the constructor just as they would if they came from the vector.
I see. That makes more sense.
So much to do to avoid memory leaks
Parts of my days are spent bug fixing...err. I’m sorry...I’ve just been reminded that we don’t have bugs. We have undocumented features. (Jonathan Ackley on Monkey Island 3)
Still easier than managing the memory yourself, especially once you've used the tools a few times and you are more familiar with them.