c++ - 计算动态分配的问题。 C++

标签 c++ memory-management

<分区>

嘿,我写了代码,但我不知道为什么它不起作用,它应该计算内存预留的数量,但我做错了什么(我的意思是没有内存分配等于 0 在两个柜台),我无法发现问题,我将不胜感激任何帮助。第一次在这里发帖,请耐心等待。 :D

#include <iostream>
#include <vector>
using std::cout; using std::endl;
struct A
{
    int a;
    static int nr;
    void * operator new[](std::size_t n) {++nr; return ::new char[n]; }
};
struct B
{
    double b;
    static int nr;
    void * operator new[](std::size_t n) {++nr; return ::new char[n]; }
};
int A::nr = 0, B::nr = 0;
int main()
{
    std::vector<A> vecA;
    std::vector<B> vecB;
    for (int i{}; i < 1000; i++)
    {
        vecA.push_back(A());
        vecB.push_back(B());
    }
    cout << "Size of vecA: " << vecA.size() * sizeof(A) << ", number of times that memory was allocated: " << A::nr << endl;
    cout << "Size of vecB: " << vecB.size() * sizeof(B) << ", number of times that memory was allocated: " << B::nr << endl;

    return 0;
}

最佳答案

为了计算内存重新分配的数量,我只看到了自己的分配器类的创建。像这样的东西:

template <typename T>
class countingAllocator : public std::allocator<T>
{
public:

   template<typename _Tp1>
   struct rebind
   {
      typedef countingAllocator<_Tp1> other;
   };

   T* allocate(size_t n, const void *hint = 0)
   {
      T::nr++;
      return std::allocator<T>::allocate(n, hint);
   }

   countingAllocator() : std::allocator<T>()
   { }

   countingAllocator(const countingAllocator &a) : std::allocator<T>(a)
   { }

   template <class U>
   countingAllocator(const countingAllocator<U> &a) : std::allocator<T>(a)
   { }
   ~countingAllocator()
   { }
};

// Fix for VS Debug build Don`t need for Release
template <>
class countingAllocator<std::_Container_proxy> : public 
  std::allocator<std::_Container_proxy>
{
public:
   template <class U>
   countingAllocator(const countingAllocator<U> &a) : 
     std::allocator<std::_Container_proxy>(a)
   { }
};


std::vector<A, countingAllocator<A>> vecA;
std::vector<B, countingAllocator<B>> vecB;
for (int i{}; i < 1000; i++)
{
    vecA.push_back(A());
    vecB.push_back(B());
}

输出:

Size of vecA: 4000, number of times that memory was allocated: 18
Size of vecB: 8000, number of times that memory was allocated: 18

关于c++ - 计算动态分配的问题。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767236/

相关文章:

c++ - wcstombs_s(),转换后的字符串长度

c++ - 为什么在 GCC 4.4.1 中我不能在函数模板中声明默认参数?

c++ - 转换一个值为 255 的 char 会导致 unsigned int 值为 4294967295,这是什么原因?

c# - MonoTouch : App killed for low mem, 为什么?事件字节分配 5 MB 顶部

memory-management - 差异交换和分页

c++ - 使用 insert c++ 增加 map 中的值

c++ - 如何将带有指针数组的 C++ 类传递给 CUDA?

c++ - 如果我忘记在 C++ 中释放内存会发生什么

c++ - 删除指针数组而不删除内存中的指向对象?

iphone - 缓存的 UITableView 元素