safe dereferencing and deletion
- by serejko
Hi, I'm relatively new to C++ and OOP in general and currently trying to make such a class that allows to dereference and delete a dead or invalid pointer without any care of having undefined behavior or program fault in result, and I want to ask you is it a good idea and is there something similar which is already implemented by someone else? or maybe I'm doing something completely wrong?
I've just started making it and here is the code I currently have:
template<class T> class SafeDeref
{
public:
T& operator *()
{
hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));
if (it != theStore.end())
return *this;
return theDefaultObject;
}
T* operator ->()
{
hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));
if (it != theStore.end())
return this;
return &theDefaultObject;
}
void* operator new(size_t size)
{
void* ptr = malloc(size * sizeof(T));
if (ptr != 0)
theStore.insert(reinterpret_cast<T*>(ptr));
return ptr;
}
void operator delete(void* ptr)
{
hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));
if (it != theStore.end()) {
theStore.erase(it);
free(ptr);
}
}
protected:
static bool isInStore(T* ptr)
{
return theStore.find(ptr) != theStore.end();
}
private:
static T theDefaultObject;
static hash_set<T*> theStore;
};
The idea is that each class with the safe dereference should be inherited from it like this:
class Foo
: public SafeDeref<Foo>
{
void doSomething();
};
So... Any advices?
Thanks in advance.
P.S. If you're wondering why I need this... well, I'm creating a set of native functions for some scripting environment, and all of them use pointers to internally allocated objects as handles to them and they're able to delete them as well (input data can be wrong), so this is kinda protection from damaging host application's memory
And I really sorry for my bad English