The complete process for an object construct of C + + is to allocate memory and initialization, which is also the function of the new keyword, which can be implemented by overloading the new operator, and system initialization can be done by invoking the constructor. We can't change the functionality of the New keyword, but we can change the way we allocate memory.
- Overloading of the new operator
The overloads of the new operator have a formal parameter that allocates memory size by default, but can add new parameters according to actual needs.
void* operator new (size_t size) {cout << "a::new ()" << Endl;return malloc (size);} void* operator new (size_t size,void *ptr) {cout << "a::new (PTR)" << Endl;return ptr;} void* operator new (size_t size,void *ptr,size_t ss) {cout << "a::new (PTR,SS)" << Endl;return ptr;}
This can be done in the following ways when the system is initialized:
A *pa = new A (), void *ptr = operator new (sizeof (A)); A *pb = new (Ptr,sizeof (a)) a (),//a *PB = new (PTR) a ();
All the arguments are placed after the New keyword
2. The Delete keyword has the function of calling destructors and freeing up memory, as with the new keyword, and we can also overload the delete operator.
The delete operator overload is simple (and can carry parameters, of course), and is typically overloaded in the following way:
void operator delete (void *ptr) {cout << "A::d elete ()" << endl;free (PTR);}
The method is called as follows:
Pb->~a ();//explicitly complete the DELETE keyword function a::operator delete (PTR);d elete pa;//Direct call
New and delete in C + + (ii)