Reputation: 591
I've an STL like implementation of a map with pointer as keys. As I noticed the keys won't get freed by the map. Because I cannot keep references to all pointers I can not manage the memory myself. I read something about smart pointers raising two questions:
Thanks for your help.
Upvotes: 0
Views: 3125
Reputation: 22134
In C++11 smart pointers is the only auto memory management.
Yes, std::shared_ptr will delete the memory when the last reference to the key is removed.
You should use strings instead of dynamically allocated char arrays. Strings is auto managed memory. It won't be convenient to use shared_ptr with dynamically allocated arrays of chars. A shared_ptr is good to manage objects.
Upvotes: 0
Reputation: 44238
If you use smart pointer as a key in a std::map
without custom comparator, then it does not work, as you simply would not replace one object with another, as pointer to one object is not equivalent to another and replace would not occur. If you do use comparator then it still would not work automatically, as key is a constant and only value modified when you replace item in a map. So I think you have 3 ways to fix your issue (assuming you do use custom comparator):
std::map
but when replacing element remove previous key/value pair first and insert new pair, do not use operator[] or assignment to iterator->second
std::map
but keep smart pointer and data in value
part and copy key from your object.replace
method.Upvotes: 2
Reputation: 5459
Presumably the keys are something in the object that your pointers point to and not the pointers themselves. If so, and you don't want to use smart pointers for whatever reason, when you erase a map element, delete the object. And don't forget to delete them all when the map is freed. And don't forget to handle copy constructor and assignment operator etc.
Upvotes: 0