sample code about overloading new and delete

mem.h

#ifndef _MEM_H__
#define _MEM_H__

#define TRACE_MEMORY

#ifdef TRACE_MEMORY

void* operator new(unsigned int size, const char *file, int line);
void* operator new[](unsigned int size, const char *file, int line);

void  operator delete(void * pointer);
void  operator delete[](void * pointer);
void  operator delete(void * p, const char *file, int line);
void  operator delete[](void * p, const char *file, int line);


#undef  DEBUG_NEW
#undef new
#define DEBUG_NEW   new(__FILE__, __LINE__)
#define new DEBUG_NEW
#endif

#endif


  

mem.cpp 

#define  _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>

void * operator new(unsigned int size, const char *file, int line)
{
	static int alloc_index = 0;

	if ( 0 == size )
	{
		return (void*)0;
	}

	void* ptr = (void*)malloc( size );
	if ( ptr )
	{
		alloc_index++;
		printf("new\t%d\t%d\n", alloc_index, (unsigned int)ptr );
	}

	return ptr;
}

void * operator new[](unsigned int size, const char *file, int line)
{
	return operator new( size, file, line );
}

void operator delete (void * pointer)
{
	static int delete_index = 0;

	if( 0 != pointer )
	{
		free(pointer);
		delete_index++;

		printf("delete\t%d\t%d\n", delete_index, (unsigned int)pointer );
	}
}

void operator delete[] (void * pointer)
{
	operator delete( pointer );
}

void operator delete(void * p, const char *file, int line)
{
	;
}

void operator delete[](void * p, const char *file, int line)
{
	;
}


 

demo.cpp 

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>

#include "mem.h"

class MyClass
{
public:
	int data[100];

	MyClass();
	~MyClass();
};


MyClass::MyClass()
{
	printf("c");
}

MyClass::~MyClass()
{
	printf("d");
}


void mem_test()
{
	MyClass* ptr = new MyClass;
	printf("\n");
	delete ptr;

	printf("\nmulti\n");

	ptr = new MyClass[5];

	printf("\ncalling\n");

	delete[] ptr;

	printf("\nend\n");
}


 

When mixing MFC(or using your own overloading-versioned new/delete) and STL one always has to be carefull of #include placements.
It can happen when you place includes for header files that use STL after MFC's macros that override operator 'new'

For example, suppose you have a class CMyClass that uses STL and it has corresponding myclass.h file.
Suppose also you have a MFC file (somemfc.cpp) that uses CMyClass. You need to make sure you put #include "myclass.h"  BEFORE  #define new DEBUG_NEW statements!
For example code below will compile OK:

#include  "myclass.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


发布了15 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/mountain_high/article/details/8896657