3 c++
给出以下代码:
int i;
...
ostingstream os;
os<<i;
string s=os.str();
Run Code Online (Sandbox Code Playgroud)
我想用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";
}
Run Code Online (Sandbox Code Playgroud)
在我的环境(Ubuntu 10.4.3,g ++)中,答案是"2".
当new运算符用于分配内置类型的对象,类类型的对象(不包含用户定义的运算符新函数)和任何类型的数组时,将调用全局运算符new函数.当new运算符用于分配定义了operator new的类类型的对象时,将调用该类的operator new.
所以每个new-expression都会调用全局operator new,除非有一个类operator new.对于您列出的课程,我认为没有课程级别operator new.
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |