/*File : operator_new.cpp *Auth : sjin *Date : 2014-04-27 *Mail : 413977243@qq.com */ #include <iostream> using namespace std; class test { public: test(){cout << "*****构造test()*****"<< endl;}; ~test(){cout << "+++++析构test()+++++"<< endl;}; }; int main() { test * x = new test;//执行分配空间,再执行析构函数 delete x;//先执行析构函数,在释放空间 }
/*File : operator_new.cpp *Auth : sjin *Date : 2014-04-27 *Mail : 413977243@qq.com */ #include <iostream> using namespace std; char mem[10000] = {‘\0‘}; int pos = 0; class test { public: test(){cout << "*****构造test()*****"<< endl;}; ~test(){cout << "+++++析构test()+++++"<< endl;}; public: void * operator new(size_t bytes){ cout << "------new test()------" << endl; int alloc = pos; pos += bytes; return (mem + alloc); }; void operator delete(void *){ cout << "------delete test()------" << endl; }; }; int main() { test * x = new test; delete x; }
/*File : operator_new.cpp *Auth : sjin *Date : 2014-04-27 *Mail : 413977243@qq.com */ #include <iostream> using namespace std; char mem[10000] = {‘\0‘}; int pos = 0; class test { public: test(){cout << "*****构造test()*****"<< endl;}; ~test(){cout << "+++++析构test()+++++"<< endl;}; public: void * operator new(size_t bytes){ cout << "------new test()------" << endl; int alloc = pos; pos += bytes; return (mem + alloc); }; void operator delete(void *){ cout << "------delete test()------" << endl; }; }; int main() { test * x = new test; delete x; x = new test[3]; delete [] x;//这里对数组释放,需要注意 }
#include <iostream> using namespace std; char mem[10000] = {‘\0‘}; int pos = 0; class test { public: test(){cout << "*****构造test()*****"<< endl;}; ~test(){cout << "+++++析构test()+++++"<< endl;}; public: void * operator new(size_t bytes){ cout << "------new test()------" << endl; int alloc = pos; pos += bytes; return (mem + alloc); }; void operator delete(void *){ cout << "------delete test()------" << endl; }; void * operator new[](size_t bytes){ cout << "------new test()------" << endl; int alloc = pos; pos += bytes; return (mem + alloc); }; void operator delete[](void *){ cout << "------delete test()------" << endl; }; }; int main() { test * x = new test; delete x; x = new test[3]; delete [] x; }
走进C++程序世界-----operator new delete 重载,码迷,mamicode.com
走进C++程序世界-----operator new delete 重载
原文地址:http://blog.csdn.net/sjin_1314/article/details/24603719