如何统计应用中内存的消耗以及内存的泄露问题,可以通过对某个类重载new和delete方法来监控对象的创建和销毁。
#include <iostream>
#include <string>
#include <memory>
// 内存分配监控
struct AllocationMetrics {
uint32_t totalAllocated = 0;
uint32_t totalFreed = 0;
uint32_t currentUsage() {
return totalAllocated - totalFreed;
}
};
static AllocationMetrics s_AllocationMetrics;
// 待监控的类
class Person {
public:
int x,y,z;
// 重载new方法
void *operator new(size_t size) {
std::cout << "分配了" << size << "bytes\n" << std::endl;
s_AllocationMetrics.totalAllocated += size;
return malloc(size);
}
// 重载delete方法
void operator delete(void *memory, size_t size) {
std::cout << "释放了" << size << std::endl;
s_AllocationMetrics.totalFreed += size;
free(memory);
}
};
static void printMemoryUsage() {
std::cout << "Memory Usage: " << s_AllocationMetrics.currentUsage() << std::endl;
}
int main() {
printMemoryUsage();
{
std::unique_ptr<Person> personPtr = std::make_unique<Person>();
}
printMemoryUsage();
Person* person1 = new Person();
printMemoryUsage();
Person* person2 = new Person();
printMemoryUsage();
delete person1;
printMemoryUsage();
return 0;
}