There are three ways to create objects in c++
Combined with the code
1 #include <iostream> 2 using namespace std; 3 class Test { 4 5 private: 6 public: 7 add() 8 { 9 int x,y,sum; 10 x=5; 11 y=5; 12 sum=x+y; 13 cout<<sum<<endl; 14 } 15 }; 16 void main() 17 { 18 Test test1; //Allocate on the stack, allocate and manage memory by the operating system 19 Test test2 = Test; //allocated in the stack,Memory allocation and management by the operating system 20 Test *test3=new Test(); //Allocation in the heap, the administrator allocates and manages memory. You must delete() after use, otherwise it may cause memory leakage. 21 (); 22 ();//"." is a reference to a structure member
23 test3->add();//"->" is a pointer reference24 delete(test3); 25 system("pause"); 26 }
There is no difference between the first and the second ones, one implicitly calls and one explicitly calls. Both are allocated memory in the stack in the virtual address space of the process.。The stack is the system data structure, for threads/processes, its allocation and release are unique byoperating systemDecisions do not need to be managed by developers. When executing a function, the storage units of local variables in the function can be created on the stack. After the function is executed, the system will automatically release these storage units.The third type uses new, and memory is allocated in the heap. Memory allocation on the heap, also known as dynamic memory allocation. During the run, the program uses malloc to apply for memory. This part of the memory is managed by the programmer himself. The lifetime of the program is determined by the developer: when to allocate, how much to allocate, and when to use free to free the memory. This is the only memory that can be managed by developers. The quality of use directly determines the performance and stability of the system.Note: The allocation and management of memory in the stack is determined by the operating system, while the allocation and management of memory in the heap is determined by the manager.
We need very little memory, and you can determine how much memory you need when using the stack. Use heap when you need to know how much memory you need at runtime.
Regarding the characteristics of new creation class objects:
- Create a new class object requires pointer reception, initialization in one place, and use in multiple places.
- New class object needs to be deleted after using it
- Create new objects directly using heap space, while creating new objects without using new to define the class object locally, use stack space
- New object pointers are widely used, such as function return value, function parameters, etc.
- Frequent calls are not suitable for new, just like new requests and frees memory.