Memory management area is divided into static storage area, stack, heap. The program is compiled to perform logic that requires global variables, local variables, object, function calls, class calls, static variables, and methods.

Stack structure suitable for representing function calls. The heap is suitable for object storage.

The actions to manage heap memory are

  1. Request (Newly requested memory must be physically contiguous).
  2. Delete (merge discrete chunks of memory, triggered automatically by the memory manager).
  3. Find unused memory blocks for garbage collection.

RAII (Resource Acquisition Is Initialization) Is a unique memory management method in c++.

The technique of using local objects to manage resources is called resource fetching and initialization. Resources here mainly refer to the limited things in the operating system, such as memory, network sockets and so on. Local objects refer to objects stored in the stack, whose life cycle is managed by the operating system without manual intervention.

The use of resources generally goes through three steps: a. Obtain resources b. Use resources C. Destroy resources, but the destruction of resources is often forgotten by programmers, so the program community wants to make the automatic destruction of resources in programmers? The father of c++ proposed a solution to the problem: RAII, which makes full use of the c++ language’s local object auto-destruction feature to control the life cycle of resources. To give a simple example of the auto-destruct feature of a local object:

#include <iostream>
using namespace std;
class person {
  public:
      person(const std::string name = "".int age = 0) : 
      name_(name), age_(age) {
            std::cout << "Init a person!" << std::endl;
      }
      ~person() {
            std::cout << "Destory a person!" << std::endl;
      }
      const std::string& getname(a) const {
            return this->name_;
      }    
      int getage(a) const {
            return this->age_;
      }      
  private:
      const std::string name_;
      int age_;  
};
int main(a) {
    person p;
    return 0; } build and run: g++ person. CPP -o person. /person Destory a person!Copy the code

As can be seen from the Person class, when we declare a local object in the main function, the constructor will be automatically called to initialize the object. When the whole main function is executed, the destructor will be automatically called to destroy the object. The whole process is completed by the operating system without manual intervention. Therefore, it is natural to think that when we use a resource, we initialize it in the constructor and destroy it in the destructor.

Reference:

Time.geekbang.org/column/arti…

zhuanlan.zhihu.com/p/34660259