namespace memory_control
{
class MemoryMonitor
{
public:
unsigned int allocaledMemorySize;
unsigned int AllocationCount;
/*
* string - type name
* unsigned int - allocation count for this type
*/
map<string, unsigned int> AllocatedTypes;
MemoryMonitor()
{
allocaledMemorySize = 0;
AllocationCount = 0;
}
bool AllMemoryIsFree()
{
return AllocationCount == 0;
}
~MemoryMonitor()
{
if (!AllMemoryIsFree())
{
cerr << "Not all allocated memory is not free!" << endl;
}
}
void MakeReport()
{
ofstream logFile("log.txt");
logFile << "Memory Monitor Report" << endl;
logFile << "----------------- Allocated types -----------------" << endl;
for (auto type = AllocatedTypes.begin(); type != AllocatedTypes.end(); type++)
{
logFile << type->first << ": " << type->second << " allocations" << endl;
}
logFile << "Total used Memory: " << allocaledMemorySize << " bytes" << endl;
logFile.close();
}
};
MemoryMonitor memoryMonitor;
template<typename T, typename... Args>
T* Malloc(Args&&... args)
{
T* pointer = new T(args...);
memoryMonitor.AllocationCount++;
memoryMonitor.allocaledMemorySize += sizeof(T);
string typeName = typeid(T).name();
auto it = memoryMonitor.AllocatedTypes.find(typeName);
if (it == memoryMonitor.AllocatedTypes.end())
{
memoryMonitor.AllocatedTypes.emplace(typeName, 1);
}
else
{
it->second++;
}
return pointer;
}
template<typename T>
void Free(T* pointer)
{
delete pointer;
pointer = nullptr;
memoryMonitor.AllocationCount--;
}
};