aQuip
aQuip

Reputation: 591

C++ map with pointer as key. Memory management

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:

  1. Is there another way to get auto memory management except of using smart pointer?
  2. Will smart pointer like Boosts Smart Pointer will free my memory when the key is not longer present, or overridden by another pointer in the map?

Thanks for your help.

Upvotes: 0

Views: 3125

Answers (3)

chmike
chmike

Reputation: 22134

  1. In C++11 smart pointers is the only auto memory management.

  2. 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

Slava
Slava

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):

  1. Still use 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
  2. Still use std::map but keep smart pointer and data in value part and copy key from your object.
  3. Use different container, for example Boost.Multi-index. You may not need multiple indexes but this container allows using part of object as a key and replace method.

Upvotes: 2

mark
mark

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

Related Questions