07.2 Three ways to create objects in C++

There are three ways to create objects in C++

#include <iostream>  
using namespace std;  
class A  
{  
private:  
    int n;  
public:  
    A(int m):n(m)  
    { }  
    ~A(){}  
};  
intmain()  
{  
    A a(1); //allocated on the stack  
    A b = A(1); //allocated on the stack  
    A* c = new A(1); //allocated in heap  
  delete c;  
    return 0;  
}  
     There is no difference between the first and the second, an implicit call and an explicit call, both of which allocate memory on the stack in the process virtual address space, while the third uses new and allocates memory on the heap , and the allocation and release of memory in the stack is managed by the system, while the allocation and release of memory in the heap must be manually released by the programmer. When using the third method, you must pay attention to the following issues:
  1. New to create a class object requires pointer reception, initialization in one place, and use in multiple places
  2. The new created class object needs to be deleted after use
  3. The new created object directly uses the heap space, while the local class object is not defined using new and uses the stack space
  4. The new object pointer is widely used, such as as a function return value, function parameters, etc.
  5. Frequent calls are not suitable for new, just like new application and release of memory
  6. The size of the stack is much smaller than the size of the heap
  7. The stack is a data structure provided by the machine system. The computer will provide support for the stack at the bottom layer: allocating a special register to store the address of the stack, and pressing and popping out of the stack have special instructions to execute, which determines the high efficiency of the stack. The heap is provided by the C/C++ function library, and its mechanism is very complicated. For example, in order to allocate a piece of memory, the library function will search the heap memory according to a certain algorithm (for the specific algorithm, please refer to the data structure/operating system). If there is not enough space (probably due to too much memory fragmentation), it is possible to call system functions to increase the memory space of the program data segment, so that there is a chance to allocate enough memory, and then proceed to return. Obviously, the heap is much less efficient than the stack.

Original link

https://blog.csdn.net/azhexg/article/details/14225545

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939596&siteId=291194637