Hi there,

I'm writing a bunch of classes like Form, Button, etc. All these are derived from a base Object class. I want to make these objects auto-delete, so I only have to declare the new keyword, and the program will clean them when necessary. I understand the implications of dereferencing, I just have a couple of questions about my code.

I through this run-down example together:
Code:
#include <Windows.h>
#include <map>

class Object
{
public:
	Object() {};
	~Object() {};

	void *operator new(size_t size);
	void operator delete(void *ptr);
	void Dispose();
	
private:
	static std::map<Object *, bool> m_Dynamic;
};

void *Object::operator new(size_t size)
{
	Object *newObj = (Object *)malloc(size);
	m_Dynamic.insert(std::pair<Object *, bool>(newObj, true));
	return newObj;
};

void Object::operator delete(void *ptr)
{
	m_Dynamic.erase((Object *)ptr);
	free(ptr);
};

void Object::Dispose()
{
	if (m_Dynamic[this])
		delete this;
};

std::map<Object *, bool> Object::m_Dynamic;		// Initialise static variable

class Circle: public Object
{
public:
	Circle() {};
	~Circle() {};

	void Destroy();

private:
	int m_Unused[10];
};

void Circle::Destroy()
{
	Object::Dispose();
}

int WINAPI WinMain(HINSTANCE hThisInstance,	HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	Circle *obj = new Circle();

	obj->Dispose();	// indirectly delete object

	return 0;
};
I have added a static variable of std::map type called m_Dynamic. I have overloaded the new and delete keywords (within the Object class) to keep the m_Dynamic map up-to-date. This prevents objects created on the stack from being deleted.

The object itself can then be deleted via the base Dispose() method. Or methods such as Destroy() can be added in derived classes and call upon Object::Dispose() themselves. This can be overloaded, etc, but eventually will be removed from the public view. I only have it here for testing.

From what I can tell everything "works", though I'm uncertain that the object is being correctly deleted.

Though, my main concern is that when a derived class such as Circle calls Dispose() which in turns fires delete this. Does it free() the sizeof(Object) or does it correctly free() the sizeof(Circle)?

Are there any other things I should be vary of? I only just started playing with new/delete overloading yesterday.

Thanks!