So i wrote a class that implements a Balanced Tree, the elements in the tree are key,value pairs. So you could add <int,string> to the tree as well as <int,int>, etc..
The problem is, when destroying the tree and either the key or the value is dynamically allocated, i'm having a memory leak.
If we take for instance: BalancedTree<int,Block*>, the Block isn't deleted, causing a memory leak.
I also can't just delete the key and value because if the key or value isn't dynamically allocated using delete would result in an error.
I think you might actually be asking too much of your class, a memory leak of the type you're describing is kind of unavoidable. I don't think it's reasonable to expect a class that can contain a load of pointers to try and delete them all when it gets destroyed. Take for example the vector container, if you had vector<Block*> and stuck a load of pointers into it, you wouldn't expect it to delete them when you called vector<Block*>::clear(). The responsibility for cleaning up the pointers lies with whoever allocated it. That said, what you're saying may not be impossible to do. I think you could make a class specialization for your template of type Block* that would automatically delete them when the tree gets destroyed.
Imho if you have a container class that will contain other objects that you want to get deleted when the container is destroyed, the container itself should have the responsibility for allocating it as well. In your case you could implement a BalancedTree for Block objects that had a method like
BalancedTree::AddBlock(some arguments)
That's my two cents anyway. maybe someone with more c++ knowledge might have something up their sleeve
So would this be possible: BalancedTree<K*,T*> ?
Basically an Add-method would look like this:
1 2 3
BalancedTree<K*,T*>::add(K,T){
//dynamically create a new K and a new T
}
So adding would actually be making a deepcopy of the key-value pair...
And when i then destroy the tree i delete every K* and T* in the tree...
Like that it would be the responsibility of the tree to allocate and free the memory taken by the tree right ? Or is this still not possible when you add only int's to the tree?
hmm I think that function there would not be particularly sensible, since if you are passing K and T by value, then there is no point in making the tree have type <K*, T*> you might as well make it a BalancedTree<K, T>, in which case you would not have to worry about deleting your K and T objects.
I'm not entirely sure what you're trying to achieve here, why would it not make sense to just make a BalancedTree<int, Block> object instead of an <int, Block*> one?