Re: memory size allocated by new
In case anybody is interested, here is a complete and tested version
of what I was describing above.
<headerFile>
/**************************************************************
* Written by Adrian Hawryluk (C) Mar 6, 2007
* -------------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj(3);
* cout << allocBase::totalBytesAllocated() // 4
* << endl
* << "*integer = " << *integer << endl;
* delete integer;
*
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() // 84 (80 + 4)
* << endl
* << "*intArray = " << *intArray << endl;
* delete[] intArray;
*
* // Class located outside of the function where this code
* // is running.
* class foo {
* int bar;
* public:
* ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() // 168? (84? + 84)
* << endl;
* // ? indicates that the returned value is compiler dependent
* delete[] fooArray;
*
**************************************************************/
class allocBase
{
protected:
static size_t bytesAllocatedSoFar;
public:
static size_t totalBytesAllocated() { return bytesAllocatedSoFar; }
};
template<class T>
class alloc : public allocBase {
T obj;
void * operator new(size_t size)
{
bytesAllocatedSoFar += size;
return ::operator new(size);
}
void * operator new[](size_t size) {
bytesAllocatedSoFar += size;
return ::operator new(size);
}
public:
static T* newObj()
{
return reinterpret_cast<T*>(new alloc<T>());
}
static T* newObjArray(int numberOfElements)
{
return reinterpret_cast<T*>(new alloc<T>[numberOfElements]());
}
// creates a new object and assigns it the value objToCopy
// requires that T::operator=(T const&) or copy constructor is
defined
static T* newObj(T const & objToCopy)
{
T* tmp = reinterpret_cast<T*>(new alloc<T>());
*tmp = objToCopy;
return tmp;
}
};
</headerFile>
<sourceFile>
size_t allocBase::bytesAllocatedSoFar = 0;
</sourceFile>
Enjoy.
Adrian