I am trying to create a tracking class to track the memory allocation. e.g print how many bytes are allocated in the application. For the variables that using new/delete operator. I could use operator new/delete. But how about the memory allocated by smart pointers?
#include <memory>
#include <iostream>
using namespace std;
template<T>
class MemoryTracking : std::enable_shared_from_this<MemoryTracking<T> >
{
public:
static size_t s_total;
void* operator new (const size_t s)
{
s_total += s;
return ::operator new[](s);
}
void* operator new[](const size_t s)
{
s_total +=s;
return ::operator new[](s);
}
void delete(void *p, size_t s) noexcept
{
s_total -= s;
::operator delete(p);
}
void delete[](void *p, size_t s) noexcept
{
s_total -= s;
::operator delete[](p);
}
// for shared_ptr
MemoryTracking() throw() {};
MemoryTracking(const MemoryTracking& other) throw() {};
MemoryTracking<T>& operator = (const MemoryTracking<T>& other) { return *this; }
MemoryTracking<T>& operator = (const MemoryTracking& other) { return *this; }
~MemoryTracking() {}
T* allocate(size_t n, const void* hint = 0)
{
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* ptr, size_t n)
{
::operator delete(ptr);
}
template <typename U>
inline bool operator == (const MemoryTracking<U>&)
{
return true;
}
template <typename U>
inline bool operator != (const MemoryTracking<U>& obj)
{
return !(*shared_from_this() == obj);
}
};
class A : public MemoryTracking<A>
{
}
int main()
{
auto ptr = make_shared<A>();
cout << MemoryTracking::s_total << endl;
}