赞
踩
测试代码:
- // test.cpp : 定义控制台应用程序的入口点。
- //
-
- #include "stdafx.h"
- #include <cstdlib>
- #include <new>
- #include <iostream>
- using namespace std;
-
- class test{
- public:
- int a;
- double x;
- test(int i,double m):a(i),x(m)
- {
- printf("creating test\n");
- };
-
- void* operator new(size_t sz)
- {
- cout<<"new: size_t "<<sz<<endl<<"sizeof(test): "<<sizeof(test)<<endl;
- return malloc(sizeof(test));
- }
-
- void operator delete(void* p)
- {
- cout<<"free:"<<endl;
- free(p);
- p=0;
- }
- };
-
- int _tmain(int argc, _TCHAR* argv[])
- {
-
- test* te=new test(1,12);
- delete te;
-
- test* te1=new test(2,10);
- delete te1;
-
- return 0;
- }

new函数虽然没有显示的表明是static的,但是它确实是static函数,可以直接调用。
在delete te;时,首先析构函数被调用,然后是test中的delete函数被调用。
new[] 和 delete[] 同样的道理。先分配一整块内存,对每一个进行构造。再对每一个进行析构,然后free整块内存。
在进行malloc的时候,实际分配的内存要比真正需要的内存大,用于存放块的一些信息。
free的时候通过这些信息,确定需要free的空间的大小。
- // test.cpp : 定义控制台应用程序的入口点。
- //
-
- #include "stdafx.h"
- #include <cstdlib>
- #include <new>
- #include <iostream>
- using namespace std;
-
- class test{
- public:
- int a;
- double x;
- test()
- {
- a=0;
- x=0.0;
- printf("test();\n");
- }
- test(int i,double m):a(i),x(m)
- {
- printf("test(int i,double m);\n");
- };
-
- ~test()
- {
- cout<<"~test()"<<endl;
- }
-
- void* operator new(size_t sz)
- {
- cout<<"new"<<sz<<endl<<"sizeof(test): "<<sizeof(test)<<endl;
- void * p=malloc(sz);
- return p;
- }
-
- void* operator new[](size_t sz)
- {
- cout<<"new[]"<<sz<<endl<<"sizeof(test): "<<sizeof(test)<<endl;
- void * p=malloc(sz);
- return p;
- }
-
- void operator delete(void* p)
- {
- cout<<"delete"<<endl;
- free(p);
- p=0;
- }
-
- void operator delete[](void* p)
- {
- cout<<"delete[]"<<endl;
- free(p);
- p=0;
- }
- };
-
- int _tmain(int argc, _TCHAR* argv[])
- {
-
- test* te=new test[12];
- delete []te;
-
- test* te1=new test[10];
- delete []te1;
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。