Dynamic Object creation, Dynamic Object
C ++ Dynamic Object Creation
Object Creation
When creating a C ++ object, two things occur:
(1) allocate memory for objects
(2) Call the constructor to initialize the memory.
However, allocating memory to objects can take place in the following ways or at an optional time:
(1) In the static storage area, the storage space can be allocated before the program starts. This bucket exists throughout the runtime.
(2) the storage unit can be created on the stack whenever it reaches a Special execution point (left braces. The execution point (right braces) is displayed, and the storage unit is automatically released. These stack allocation operations are embedded in the processor's instruction set and are very effective. However, when writing a program, you must know how many storage units are needed so that the compiler knows how to generate correct commands.
(3) a storage unit can also be calledHeap. This is called dynamic memory allocation. Call the program to allocate the memory at runtime. This means that the memory can be allocated and the amount of memory allocated at any time. Of course, you need to decide when to release the memory.
C. How to obtain a storage unit from the heap
To dynamically allocate memory at runtime, C provides some functions in its standard library functions: the malloc () function applied for memory from the heap and Its Variant calloc () and realloc (), release the memory and return it to the heap function free (). Here is an example:
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 class Obj11 {12 public:13 void initialize() {14 cout<< "initializing Obj" <<endl;15 i = j = k = 0 ;16 memset(buf, 0, sz);17 }18 void destroy() const {19 cout<< "destroying Obj" <<endl;20 }21 private:22 int i, j, k;23 enum {sz=100};24 char buf[sz];25 };26 27 int main()28 {29 Obj* obj = (Obj*)malloc(sizeof(Obj));30 obj->initialize();31 obj->destroy();32 free(obj);33 return 0;34 }
The program has such a line of code that uses malloc () to allocate memory for the object:
1 Obj* obj = (Obj*)malloc(sizeof(Obj));
Here, you must determine the object length. Because malloc () only allocates a piece of memory instead of generating an object, it returns a void * type pointer. C ++ does not allow a void * pointer to be assigned to any other pointer, So type conversion is required.
You must remember to initialize the object before using it. Note that the constructor is not used because it cannot be explicitly called-it is called by the compiler when the object is created.
Many programmers find C's dynamic memory allocation function too complex and confusing. Therefore, C programmers often use the virtual memory mechanism to allocate large variable arrays in the static memory area to avoid dynamic memory allocation. C ++ does not accept the dynamic memory allocation method of C in order to enable normal programmers to use library functions securely without any effort.
C ++'s new and delete
The solution in C ++ is to combine all the actions required to create an object into a new operator. When we create an object using the new (new expression), it allocates memory for the object in the heap and calls the constructor for this memory. We can write a new expression for the class to use any available constructor. If the constructor has no parameters, we can write a new expression without the constructor parameter table.
The opposite of the new expression is the delete expression. The delete expression first calls the Destructor and then releases the memory. If the pointer of the object being deleted is 0, nothing will happen. Therefore, we often recommend that you assign a pointer to 0 immediately after deleting the pointer so as not to delete it twice, resulting in some problems.
1 #ifndef TREE_H 2 #define TREE_H 3 #include<iostream>//Tree.h 4 using namespace std; 5 6 class Tree 7 { 8 public: 9 Tree(int treeHeight) :height(treeHeight) {}10 ~Tree() {cout<< "*" <<endl; }11 friend ostream& operator << (ostream& os, const Tree* t) {12 return os<< "Tree height is: " << t->height <<endl;13 }14 private:15 int height;16 };17 18 #endif // TREE_H
1 #include "Tree.h" 2 using namespace std; 3 4 int main() 5 { 6 Tree* t = new Tree(40); 7 cout<< t; 8 delete t; 9 return 0;10 }
Used for Array new and delete
When using new to create an object array on the stack, see the following code:
MyType* fp = new MyType[100];
In this way, the heap allocates enough memory for 100 MyType objects and calls constructors for each object. When destroying this array, we should write as follows:
delete []fp;
Empty square brackets tell the compiler to generate code. The task of this Code is to retrieve the number of objects stored in a certain place when the array is created, and call the Destructor for all objects in the array.
How to exhaust memory?
What will happen when operator new () cannot find enough contiguous memory blocks to arrange objects? A special function called new-handler will be called. First, check the pointer to the function. if the pointer is not 0, the function to which it points will be called.
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #include<new> 8 #define inf 0x7fffffff 9 using namespace std;10 11 int cnt = 0;12 13 void out_of_memory()14 {15 cerr<< "memory exhausted after " << cout << " allocations!" <<endl;16 exit(1);17 }18 19 int main()20 {21 set_new_handler(out_of_memory);22 while (1) {23 cnt ++ ;24 new int[1000];25 }26 return 0;27 }
Note: The new-handler function must not contain parameters and the return value is void. The While LOOP continues to allocate int objects until the empty memory is exhausted. In the next call to new, no memory can be called, and all new-handler functions are called.
Below
The new-handler function tries to call operator new (). If operator new () has been overloaded, new-handler will not be called by default. So if we still want to call new-handler, we have to add the code to do the work in the code of the overloaded operator new.
The next Dynamic Object creation section will explain how to overload new and delete objects.