c++ - 使用智能指针时如何跟踪内存分配

标签 c++ memory smart-pointers

我正在尝试创建一个跟踪类来跟踪内存分配。例如打印应用程序中分配了多少字节。对于使用new/delete操作符的变量。我可以使用运算符 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;
}

最佳答案

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

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

关于c++ - 使用智能指针时如何跟踪内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36950473/

相关文章:

memory - cudamemcpy 错误 :"the launch timed out and was terminated"

python - 为什么在与字符串共享 ctypes.Structure 与仅使用字符串时,子进程(python 多处理)的内存使用量如此不同?

c++ - 不匹配 ‘operator[]’(操作数类型为 ‘std::unique_ptr<std::vector<int>>’ 和 ‘int’)

c++ - 错误: 'unordered_set' is not a member of 'std'

c++ - Azure IoT Edge C++ 模块未将设备发送到云遥测

linux - 32/64 位应用程序、操作系统和处理器之间的关系是什么?

c++ - unique_ptr 运算符=

c++ - 在 C++ 中检测 Enter/Return on Keydown 事件

c++ - 使用模板访问 C++ 中父类(super class)的 protected 成员

c++ - 哈夫曼压缩器/解压器