First of all: in C++ avoid malloc
. Then you don't have to worry about whether something was allocated with malloc or new, because you never allocated anything with malloc. Although your problem isn't solved even then, because there is a difference between delete
and delete[]
for arrays... so you can't really go deleting other people's pointers for them. I suppose a good mantra would be "in destructors we trust". :)
Secondly: if you are trying to create a container class, don't hand it raw pointers if you want it to participate in resource management. Think about what happens when you make a std::vector<std::string *>
. When that vector runs its destructor, does it do anything with the pointers contained? Nope. As far as it is concerned it might as well have been holding integers. The lifetime management is assumed to be taken care of elsewhere. (At least, we hope...!)
If you do want your container to participate in lifetime management, you need to pass it objects that wrap up your pointers and speak some protocol. While you're free to define any protocol you like, the easiest protocols to work with are the ones that have already been standardized. In C++ that's things like whether your object supports copy construction, move construction, the ordinary destructor... etc. Looking to the standard library containers for inspiration is a good start.
So consider your idea of your container putting objects in a destroy queueing vector, and then calling a method to destroy them. There may be an advantage to destroying objects in batches, but why would a general purpose container care about that? Why can't the contained objects run their destructors as normal, but have that destructor put the wrapping object's content into a queue maintained by some kind of "contained object manager"? You can separate the concern from the container completely, if that's what you really need. Usually though, you just don't need it.
As mentioned by others, look into shared_ptr
and unique_ptr
if you haven't already, and you might learn something from the case of why auto_ptr was decided to be not cool