给出以下代码:
int i;
...
ostingstream os;
os<<i;
string s=os.str();
我想统计使用时动态内存分配的次数ostringstream
这边走。我怎样才能做到这一点?也许通过operator new
?
谢谢。
是的,您可以这样做:
#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”。
EDIT: Quoting
MSDN http://msdn.microsoft.com/en-us/library/t48aek43%28v=vs.71%29.aspx
当使用new运算符分配内置类型的对象、不包含用户定义的operator new函数的类类型的对象以及任意类型的数组时,会调用全局operator new函数。当 new 运算符用于分配定义了运算符 new 的类类型的对象时,将调用该类的运算符 new。
所以每个新表达式都会调用全局operator new
, unless有一个班级operator new
。对于你列出的班级,我认为没有班级级别operator new
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)