如何使用operator new来计算动态内存分配的次数

时间:2012-03-29 14:50:03

标签: c++

给出以下代码:

int i;
...
ostingstream os;
os<<i;
string s=os.str();

我想用这种方式使用ostringstream来计算动态内存分配的次数。我怎样才能做到这一点?也许通过operator new

谢谢。

3 个答案:

答案 0 :(得分:5)

是的,以下是您可以做到的方法:

#include <new>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

int number_of_allocs = 0;

void* operator new(std::size_t size) throw(std::bad_alloc) {
  ++number_of_allocs;
  void *p = malloc(size);
  if(!p) throw std::bad_alloc();
  return p;
}

void* operator new  [](std::size_t size) throw(std::bad_alloc) {
  ++number_of_allocs;
  void *p = malloc(size);
  if(!p) throw std::bad_alloc();
  return p;
}

void* operator new  [](std::size_t size, const std::nothrow_t&) throw() {
  ++number_of_allocs;
  return malloc(size);
}
void* operator new   (std::size_t size, const std::nothrow_t&) throw() {
  ++number_of_allocs;
  return malloc(size);
}


void operator delete(void* ptr) throw() { free(ptr); }
void operator delete (void* ptr, const std::nothrow_t&) throw() { free(ptr); }
void operator delete[](void* ptr) throw() { free(ptr); }
void operator delete[](void* ptr, const std::nothrow_t&) throw() { free(ptr); }

int main () {
  int start(number_of_allocs);

  // Your test code goes here:
  int i(7);
  std::ostringstream os;
  os<<i;
  std::string s=os.str();
  // End of your test code

  int end(number_of_allocs);

  std::cout << "Number of Allocs: " << end-start << "\n";
}

在我的环境(Ubuntu 10.4.3,g ++)中,答案是“2”。

<小时/> 编辑:引用MSDN

  

当new运算符用于分配内置类型的对象,类类型的对象(不包含用户定义的运算符新函数)和任何类型的数组时,将调用全局运算符new函数。当new运算符用于分配定义了operator new的类类型的对象时,将调用该类的operator new。

所以每个new-expression都会调用全局operator new,除非有一个类operator new。对于您列出的课程,我认为没有班级operator new

答案 1 :(得分:1)

如果要计算动态分配的对象, 您应该通过重载来替换类的new运算符,并在其中添加计数逻辑。

好读:
How should I write ISO C++ Standard conformant custom new and delete operators?

答案 2 :(得分:0)

如果您使用的是Linux(glibc),则可以使用a malloc hook记录所有动态内存分配。