得承认,这不困难,下面的这种做法可能看起来舒服些。
#include
namespace HL
{
class mallocHeap
{
public:
~mallocHeap (void) {}
inline void * malloc (size_t sz)
{
return ::malloc (sz);
}
inline void free (void * ptr)
{
::free (ptr);
}
inline size_t getSize (void * ptr)
{
return ::_msize (ptr);
}
};
template
class PerClassHeap
{
public:
inline void * operator new (size_t sz)
{
printf("Malloc one\n");
return getHeap()->malloc (sz);
}
inline void operator delete (void * ptr)
{
printf("delete one\n");
getHeap()->free (ptr);
}
inline void * operator new[] (size_t sz)
{
return getHeap()->malloc (sz);
}
inline void operator delete[] (void * ptr)
{
getHeap()->free (ptr);
}
// For some reason, g++ needs placement new to be overridden
// as well, at least in conjunction with use of the STL.
// Otherwise, this should be superfluous.
inline void * operator new (size_t sz, void * p) { return p; }
inline void * operator new[] (size_t sz, void * p) { return p; }
private:
inline static SuperHeap * getHeap (void)
{
static SuperHeap theHeap;
return &theHeap;
}
};
}
class TestB : public HL::PerClassHeap
{
};