Dynamic Object creation (2) Reload new, delete, newdelete

Source: Internet
Author: User

Dynamic Object creation (2) Reload new, delete, newdelete

Dynamic Object creation (2) Reload new and delete

Preface

I have briefly introduced how to create dynamic objects. The content of this article mainly explains how to reload new and delete objects, and hope to get some advice from bloggers, thank you here.

We usually use the memory allocation system of new and delete for some purposes, but in special cases, it does not meet the needs. The most common reason for changing the allocation system is to consider efficiency: it may be necessary to create and destroy a very large number of objects for a particular class so that this operation becomes a speed bottleneck. C ++ allows us to reload new and delete to implement our own storage allocation scheme, so we can use it to handle the problem.

Another problem is heap fragmentation: allocating memory of different sizes may generate many fragments on the heap, so that the memory can be used up quickly. Although the memory may still exist, but because it is all fragments, we cannot find enough memory blocks to meet our needs. By creating your own memory distributor for a specific class, you can ensure that this will not happen.

When we reload operator new () and operator delete (), We just changed the original memory allocation method. The compiler will replace the default version with the overloaded new to allocate memory, and then call the constructor for that memory. Therefore, although the compiler allocates memory and calls constructor when it sees new, it can only change the memory allocation when it reloads new.

Next, I will explain how to reload new and delete in three parts: Reload global new and delete, reload new and delete for a class, and reload new and delete for arrays.

Reload global new and delete

When we reload global new and delete, we can imagine that it will make the default versions completely inaccessible-even in this definition, they cannot be called.

The overloaded new must have a size_t parameter. This parameter is generated by the compiler and passed to us. It is the length of the object for memory allocation. A pointer to an object equal to or greater than the length must be returned. If no storage unit is found (in this case, the constructor is not called), a 0 is returned. If the storage unit cannot be found, we should call new-handler or generate an exception message to tell you that a problem has occurred.

The first thing we need to understand is that the return value of operator new () is a void * instead of pointing to any specific type of pointer. What we do is allocate memory instead of creating an object. The object is created only when the constructor calls the object. It is the action that the compiler ensures that it is not in our control scope, so we have no need to consider it.

 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #define inf 0x7fffffff 8 using namespace std; 9 10 void* operator new(size_t sz)11 {12     printf("operator new: %d Bytes\n",sz);13     void* m = malloc(sz);14     if (!m) puts("out of memory");15     return m;16 }17 18 void operator delete(void* m)19 {20     puts("operator delete");21     free(m);22 }23 24 class S25 {26 public:27     S() {puts("S::S()"); }28     ~S() {puts("S::~S()"); }29 private:30     int an[1000];31 };32 33 int main()34 {35     puts("creating & destroying an int");36     int* q = new int(23);37     delete q;38     puts("creating & destroying an int[]");39     int* p = new int[10]();40     delete []p;41     puts("creating & destroying an s");42     S* s = new S;43     delete s;44     puts("creating & destroying S[3]");45     S* sa = new S[3];46     delete []sa;47     return 0;48 }

For a class, reload new and delete

When a class is overloaded with new and delete, although you do not need to explicitly use static, you are still creating static member functions. Its syntax is the same as reloading any other operators. When the compiler sees the object that uses new to create its own defined class, it selects the member version operator new () instead of the global version new (). However, the global versions of new and delete are still used for all other types of objects (unless they also have their own new and delete ). This is the same as global variables and local variables.

 1 #include<iostream> 2 #include<cstddef> 3 #include<fstream> 4 #include<new> 5 using namespace std; 6 ofstream out("Framis.out"); 7  8 class Framis 9 {10 public:11     enum{psize = 100 };12     Framis() {out<< "Framis()" <<endl; }13     ~Framis() {out<< "~Framis() ... " <<endl; }14     void* operator new(size_t) throw (bad_alloc);15     void operator delete(void*);16 private:17     enum{sz = 10 };18     char c[sz];19     static unsigned char pool[];20     static bool alloc_map[];21 };22 unsigned char Framis::pool[psize*sizeof(Framis)];23 bool Framis::alloc_map[psize]={false};24 25 void* Framis::operator new(size_t sz) throw(bad_alloc)26 {27     for (int i=0; i<psize; ++i) {28         if (!alloc_map[i]) {29             out<< "using block " << i << " ... ";30             alloc_map[i]=true;31             return pool+(i*sizeof(Framis));32         }33     }34     out<< "out of memory" <<endl;35     throw bad_alloc();36 }37 38 void Framis::operator delete(void* m)39 {40     if (!m) return;41     unsigned long block = (unsigned long)m-(unsigned long)pool;42     block /= sizeof(Framis);43     out<< "freeing block " << block <<endl;44     alloc_map[block]=false;45 }46 47 int main()48 {49     Framis* f[Framis::psize];50     try {51         for (int i=0; i<Framis::psize; i++) {52             f[i]=new Framis;53         }54         new Framis;55     } catch(bad_alloc) {56         cerr<< "Out of memory!" <<endl;57     }58     delete f[10];59     f[10]=0;60     Framis* X=new Framis;61     delete X;62     for (int j=0; j<Framis::psize; j++) {63         delete f[j];64     }65     return 0;66 }

Reload new and delete for Arrays

In the previous section, we mentioned that if operator new () and operator delete () are overloaded for a class, these operators will be called whenever an object of this class is created. However, if you want to create an object array for this class, the global operator new () will be called immediately to allocate enough memory for this array. In this regard, we can control the memory allocation of the object array through the array version of this overload operator, namely operator new [] and operator delete.

 1 #include<iostream> 2 #include<fstream> 3 #include<new> 4 using namespace std; 5 ofstream trace("ArrayOperatorNew.out"); 6  7 class Widget 8 { 9 public:10     Widget() {trace<< "*" <<endl; }11     ~Widget() {trace<< "~" <<endl; }12     void* operator new(size_t sz) {13         trace<< "Widget::new: " << sz << " byte" <<endl;14         return ::new char[sz];15     }16     void operator delete(void* p) {17         trace<< "Widget::delete" <<endl;18         ::delete []p;19     }20     void* operator new[](size_t sz) {21         trace<< "Widget::new[]: " << sz << " bytes" <<endl;22         return ::new char[sz];23     }24     void operator delete[](void* p) {25         trace<< "Widget::delete[]" <<endl;26         ::delete []p;27     }28 private:29     enum{sz=10 };30     int an[sz];31 };32 33 int main()34 {35     trace<< "new Widget" <<endl;36     Widget* w=new Widget;37     trace<<endl<< "delete Widget" <<endl;38     delete w;39     trace<<endl<< "new Widget[25]" <<endl;40     Widget* wa=new Widget[25];41     trace<<endl<< "delete []Widget" <<endl;42     delete []wa;43     return 0;44 }

Summary

1: I have a new understanding of creating dynamic objects in C ++, and I have learned how to reload new and delete objects.

2: the size of the C ++ null class is 1.

3: The most exciting thing is that the C ++ program writes the running result to the newly created document, which is different from the commonly used file read/write operations in ACM.

Okay, continue to work !!!

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.