Test code:
Test.cpp: Defines the entry point for a console application.
//
#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);
= =;
}
;
int _tmain (int argc, _tchar* argv[])
{
test* te=new Test (1,12);
Delete te;
test* te1=new Test (2,10);
Delete te1;
return 0;
}
test* te=new Test (1,12), called two functions, first called the new function of test, and then called the constructor of Test.
The new function, although not shown as static, is indeed a static function that can be invoked directly.
At Delete te, the destructor is invoked first, and then the delete function in test is invoked.
New[] and delete[] the same truth. Allocate an entire block of memory first, and construct each one. Then refactor each one, then free the entire block of memory.
In malloc, the actual memory allocated is larger than the real memory required to store some information about the block.
When free, use this information to determine the size of the space needed for free.
Test.cpp: Defines the entry point for a console application.
#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 (t
EST) <<endl;
void * P=MALLOC (SZ);
return p;
} void operator Delete (void* p) {cout<< "delete" <<endl;
Free (p);
p = =;
} void operator delete[] (void* p) {cout<< "delete[]" <<endl;
Free (p);
p = =;
}
};
int _tmain (int argc, _tchar* argv[]) {test* te=new test[12];
delete []te; test* Te1=neW TEST[10];
delete []te1;
return 0;
}