c++ 监控内存使用量

#include 
#include  
#include  
 
struct AllocationMetrics /*用来监控内存*/
{
	uint32_t TotalAllocation = 0;
	uint32_t TotalFreed = 0;

	uint32_t CurrentUsage() { return TotalAllocation - TotalFreed; }
};

static AllocationMetrics s_AllocationMetrics;

void* operator new(size_t size) {

	s_AllocationMetrics.TotalAllocation += size;
	std::cout << "Allocating " << size << "bytes" << std::endl;
	/*在该处插入断点,即可通过栈查看哪里使用了堆分配*/
	return malloc(size);
}

void operator delete(void* memery, size_t size) {
	s_AllocationMetrics.TotalFreed += size;
	std::cout << "Freeing " << size << " bytes" << std::endl;
	free(memery);
}

/*为什么用static*/
static void PrintMemeryUsage() {
	std::cout << "Memery Usage: " << s_AllocationMetrics.CurrentUsage() << " bytes\n";
}

struct Object{

	int x, y, z;
};

int main() {  
	std::string string = "Chreno";

	// Object* obj = new Object;

	std::unique_ptr<Object> obj = std::make_unique<Object>();
}

你可能感兴趣的:(总结记录c++,c++)