如何使用operator new来计算动态内存分配的次数 [英] How to use operator new to count number of times of dynamic memory allocation
问题描述
给定以下代码:
int i;
...
ostingstream os;
os<<i;
string s=os.str();
我想计算使用 ostringstream时动态内存分配的次数
这样。我该怎么办?可能通过运算符新
?
I want to count the number of times of dynamic memory allocation when using ostringstream
this way. How can I do that? Maybe through operator new
?
谢谢。
推荐答案
是的,这里是你可以做到的:
Yes, and here is how you could do it:
#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。
In my environment (Ubuntu 10.4.3, g++), the answer is "2".
EDIT :引用 MSDN
当新的操作符用于分配内置类型的对象,类类型的对象,不包含用户定义的操作符新函数,以及任何类型的数组时,全局操作符new函数被调用。当新的操作符用于分配定义了操作符new的类类型的对象时,将调用该类的操作符new。
The global operator new function is called when the new operator is used to allocate objects of built-in types, objects of class type that do not contain user-defined operator new functions, and arrays of any type. When the new operator is used to allocate objects of a class type where an operator new is defined, that class's operator new is called.
因此每个new-expression将调用全局运算符new
,除非运算符new
。对于你列出的类,我相信没有类级别运算符new
。
So every new-expression will invoke the global operator new
, unless there is a class operator new
. For the classes you listed, I believe that there is no class-level operator new
.
这篇关于如何使用operator new来计算动态内存分配的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!