#include <iostream> using namespace std; Class A { private: int n; Public: A (int m): N (m) {} ~a () {} }; int main () { A A (1); Allocate a B = A (1) in the stack; Allocate A * c = new A (1) in the stack; Allocation of delete C in the heap ; return 0; }
There is no difference between the first and the second, an implicit invocation, an explicit invocation, both allocating memory in the stack in the process virtual address space, and the third using new, allocating memory in the heap, while the allocation and release of memory in the stack is managed by the system, and the allocation and release of the memory in the heap must be manually released by the programmer. In the third approach, there are a few things to consider:
- New Create class object requires pointer reception, one initialization, multiple use
- New Create class object with delete destroy required
- The new creation object uses heap space directly, while local without new definition class object uses stack space
- New object pointers are used for a wide variety of purposes, such as function return values, function parameters, etc.
- Frequent invocation is not suitable for new, just as new applies and frees memory
- The size of the stack is much smaller than the heap
- The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has special instruction execution, which determines the efficiency of the stack is high. The heap is provided by C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.
Three ways to create objects in C + +