I was wondering if it is possible to add code (checks of the validity of the object pointed to actually) when a pointer is dereferenced.
I saw many subjects on overloading operator ->, but it seems the operator was called on an object, not a pointer. Maybe (probably) there is something I’m misunderstanding.
here’s an example :
T* pObj = new T();
pObj->DoStuff(); // call check code (not in DoStuff)
delete pObj;
pObj->DoOtherStuff(); // call check code (not in DoOtherStuff)
the “check code” should be independent from the function (or members) called. My idea was to set a member as an int in the class, and give it a defined value at construction (and destruction), then check the value.
As you may have guess I try to check for invalid pointers used. I try to read the code but it’s far too big and complex to not miss many potential errors.
Thanks for your answers and insights.
operator->can only be overloaded as a member function of a class, not for a normal pointer.In general there is no way to check that a (non-null) pointer actually points to a valid object. In your example
delete pObj;does nothing to change the pointer; it just leaves it pointing to invalid memory, and there is no way to test for that. So, even if you could overloadoperator->here, the best it could do is check that it wasn’t null.The usual approach is to use smart pointers, rather than normal pointers. A smart pointer is a class that wraps a plain pointer to an object, and has overloads of
operator*andoperator->so that it looks and feels like a pointer. You won’t delete the object directly, but through the pointer (when it goes out of scope, or explicitly by calling areset()function), and the pointer can then set its plain pointer to null when that happens. In that way, the plain pointer will always be either valid, or null, so the overloaded operators can usefully check it before dereferencing.Smart pointers (and RAII in general) bring other advantages too: automatic memory management, and exception safety. In your code, there will be a memory leak if
DoStuff()throws an exception;pObjwill go out of scope, and so there will be no way to access it to delete the object it points to. The memory will be lost and, if this keeps happening, you will eventually use all the system’s memory and either crash or slow to a crawl. If it were a smart pointer, then the object would be deleted automatically as it went out of scope.Commonly used smart pointers from the Standard Library and Boost are
auto_ptr,scoped_ptrandshared_ptr, each with different behaviour when copying the pointer. C++0x will introduceunique_ptrto replaceauto_ptr.