Skip to main content
gamedev.net
🔒 Locked

overloading delete...

Started by CJM 3 replies 900+ views
Original Post
CJM
CJM
Heya, I'm playing around with some memory managment stuffs atm, and have come up with code which uses some macro goodness to get my overloaded new to have line numbers etc attached... and was wondering if a similar thing can be done with delete. Note that this is retrospective, I want to be able to not have to explicitly state in my code operator delete(x) to get it to work. So, in the spirit of the way that new(__LINE__) int(); works, can delete be overloaded...? CJM
mike25025
mike25025
this is the only way i can think of
its not realy overloading
it also doesnt work with arrays [sad]

#include <cstdlib>#include <iostream>using namespace std;template<typename T>void fDelete(T* ptr,int line){	cout << "Deleteing " << (void*)ptr << " on line " << line << endl;	delete ptr;}class CDelete{public:	int line;	template<typename T>	CDelete& operator=(T* ptr)	{		fDelete(ptr,line);		return *this;	}};CDelete g_d;static CDelete& funcDelete(int line){	g_d.line = line;	return g_d;}#define delete funcDelete(__LINE__)=/////////////////////////////class Test{public:	Test(){cout << "Test::Test()" << endl;}	virtual ~Test(){cout << "Test::~Test()" << endl;}};int main(int argc, char *argv[]){	Test* t = new Test;	delete t;	system("PAUSE");	return 0;}
Evil Steve
Evil Steve
mmgr just uses globals for this:
#define	delete   (m_setOwner  (__FILE__,__LINE__,__FUNCTION__),false) ? m_setOwner("",0,"") : deletevoid m_setOwner(const char *file, int line, const char *func){   // Save the globals away   g_szFile = file;   g_nLine = line;   g_szFunc = func;}

And then you just have your normal operator delete, which can check those values. However, it'll run into issues with threading.
CJM
CJM
Heya,

Nice, but sort of clunky and needs to live in the header files, since it's got to be a template... Still, much better than what I was doing...

CJM
CJM
CJM
Evil Steve's response was much closer to what I was actually doing...

Except, I didn't really think about the whole ?: operator thingy, I was just making a function call and then calling delete manually regardless of what happened...

Nice,
CJM

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.