If you're absolutely worried about memory leaks, use vector's contiguous memory layout. Deconstructor takes care of memory release, removing the need for pointer-based arrays.
When allocating/instantiating a single object through a pointer though, the extra memory and speed requirement of the vector class may not be worth it.
Also, one could build a registration class which tracks memory allocation through pointers by exposing member functions that are used in proxy of direct calls to new/new[] and delete/delete[]. This way the member function can examine the existing state of the pointer in question, and deallocate it if need be before allocating.
#include <iostream>using std::cout;using std::endl;#include <new>using std::nothrow;template<class T>bool array_alloc(T *&ptr, size_t elems = 0){ // T **ptr_to is used to compare against the database. // Memory cost of tracking this pointer in the database // is sizeof(T**). T **ptr_to = &ptr; bool is_allocated = false; if(0 == elems) return is_allocated; // false // If this address is found in the database, // it is passed to delete[]. if(0 != *ptr_to) delete [] *ptr_to; // Upon failure, return 0 instead of throwing std::bad_alloc. *ptr_to = new(nothrow) T[elems*sizeof(T)]; if(0 == *ptr_to) return is_allocated; // false; else is_allocated = true; for(size_t i = 0; i < elems; i++) (*ptr_to) = 0; return is_allocated; // true}int main(void){ size_t size = 10; char *y = 0; array_alloc(y, size); cout << static_cast<int>(y[size - 1]) << endl; // When the database class goes out of scope, // all known allocated pointers are passed to delete[]. return 0;}
Edit: changed the source.
[Edited by - taby on August 5, 2007 11:57:23 PM]