New and delete in C + + (ii)

Source: Internet
Author: User

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.

    1. 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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.