I encountered this kind of issue: a possible memory leak.
Imagine if you store two different heap pointers for same key.
#include <map>
std::map<int, int*> myMap;
void Store(int key, int* value)
{
myMap[key] = value;
}
int main()
{
Store(42, new int(42));
Store(35, new int(35));
delete myMap[42];
delete myMap[35];
}
I thought about fixing that way:
#include <map>
std::map<int, int*> myMap;
void Store(int key, int* value)
{
auto it = myMap.find(key);
if (it != myMap.end()))
{
delete it->second;
it->second = value;
}
else
{
myMap[key] = value;
}
}
int main()
{
Store(42, new int(42));
Store(35, new int(35));
delete myMap[42];
delete myMap[35];
}
But there are two logarithmic look-ups instead of one now...
Then I thought about this following code,
#include <map>
std::map<int, int*> myMap;
void Store(int key, int* value)
{
auto& mappedValue = myMap[key];
if (mappedValue == nullptr)
{
mappedValue = value;
}
else
{
delete mappedValue;
mappedValue = value;
}
}
int main()
{
Store(42, new int(42));
Store(35, new int(35));
delete myMap[42];
delete myMap[35];
}
but how can I be certain mappedValue will always point to nullptr if there is no associated value ?
What would you suggest to tackle memory leak and stick with logarithmic complexity ?
EDIT: refactoring is very costy, I'm looking for a solution without smart pointers.