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
Edit: unfortunately shared_ptr and similar aren't for me... The scripting language itself (its name is Pawn by the way) is very limited and every thing there is made of 32-bit cells, and I should place in such a cell a pointer to the object. In general the man who writes a script doesn't even know of that, so when he pass an invalid value it should be detected some way and it should not do anything in that case.
Edit2: I'm feeling like I misunderstood something about shared_ptr... I will take a look at them, thank you for all your replies!
Edit3: Hmm, what I'm trying to make isn't actually for me and preventing me from stupid code or whatever, it is aimed to guard the application (which is a game server I'm writing a plugin for (they share the same address space), to extend its scripting features) from bad scripts which can cause the server to crash, I'm sorry that I didn't tell this earlier and nobody understood what I mean... Thanks for replies anyway.