如何在使用智能指针时跟踪内存分配

时间:2016-04-30 03:47:15

标签: c++ memory smart-pointers

我正在尝试创建跟踪类来跟踪内存分配。例如,打印在应用程序中分配的字节数。对于使用new / delete运算符的变量。我可以使用operator new / delete。但智能指针分配的内存怎么样?

#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;
}

1 个答案:

答案 0 :(得分:2)

如果要跟踪应用程序中分配的所有内存,您可能希望覆盖malloc()realloc()calloc()free()。通过覆盖这四个,您不仅可以捕获C ++分配,还可以捕获C分配。

有关如何包装malloc()等函数,请参阅:How to reimplement (or wrap) a syscall function in linux?Globally override malloc in visual c++