嘿,我已经编写了代码,但我不知道为什么它不起作用,它假设要计算内存预留的数量,但是我做错了什么(我的意思是,内存分配中的数量不等于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;
}
答案 0 :(得分:3)
要计算内存重新分配的数量,我只能看到创建自己的分配器类。像这样:
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
答案 1 :(得分:1)
您可以尝试以下方法:
#include <vector>
#include <iostream>
struct A
{
int a;
static int nr;
};
struct B
{
double b;
static int nr;
};
int A::nr = 0, B::nr = 0;
int main ()
{
std::vector<A> vecA;
std::vector<B> vecB;
size_t A_capacity = 0, B_capacity = 0;
for (int i{}; i < 1000; i++)
{
vecA.push_back(A());
if (vecA.capacity () != A_capacity)
{
++A::nr;
A_capacity = vecA.capacity ();
}
vecB.push_back(B());
if (vecB.capacity () != B_capacity)
{
++B::nr;
B_capacity = vecB.capacity ();
}
}
std::cout << "A: " << A::nr << ", B: " << B::nr;
}
输出:
A: 11, B: 11