Dynamic memory allocation new/delete in C++


When it comes to memory allocation in C language, we naturally think of malloc and free in the standard library functions to dynamically allocate memory space
. In C++, we provide operators new and delete to replace malloc and free for dynamic allocation of memory. space.

What is the difference and connection between malloc/free and new/delete?
1. They are the entry points for dynamic memory management.
2. malloc/free is a function of the C/C++ standard library, and new/delete is a C++ operator.
3.malloc/free just dynamically allocate memory space/release space. In addition to allocating space, new/delete will also call the constructor and destructor to initialize and clean up
4. malloc/free needs to manually calculate the size of the type and the return value will be void*, new/delete can calculate the size of the type by itself and return the corresponding type pointer.


We all know that the memory are:
1. The stack area (stack)—local variable area                                                        
2, the heap area (heap)—dynamic storage area         
3, the global area (static static area)—stores global variables, static data, and constants. Released by the system after the program ends.
4. The literal constant area—constant strings are placed here. Released by the system after the program ends.
5. The code area stores the binary code of the function body (class member function and global function) one by one.

Two forms of new:
1.new/delete dynamically manages objects.
2.new[]/delete[] dynamically manages the object array.

Code block:

int* p4 = new int; // 动态分配4个字节(1个 int)的空间单个数据
int* p5 = new int(3); // 动态分配4个字节(1个 int)的空间并初始化为3
int* p6 = new int[3]; // 动态分配12个字节(3个 int)的空间
delete p4 ;
delete p5 ;
delete[] p6 ;

Notice: 

  The new operator returns a pointer to a variable (object) of the allocated type.
 malloc/free, new/delete, new[]/delete[] must match! ! ! Otherwise, memory leaks or even crashes may occur.
Learn more about:
The above mentioned new and delete are just operators, not functions. So what does it use to dynamically apply for memory?

two standard
Its prototype 
void *operator new(size_t);        // Note that it is not overloaded! , new and delete cannot be overloaded
void *operator delete(void *);  
void *operator new[](size_t);   
void *operator delete[](void *);

New does two things
 1. Calls the operator new function to allocate space, and puts malloc into an infinite loop to apply for space. //operator new is actually the encapsulation of malloc
 2. Call the constructor to initialize the object.

delete also does two things
 1. calls the destructor to clean up the object
 2. calls the operator delete function to free up space

new[N]
 1. Call operator new to allocate space.
 2. Call the constructor N times to initialize each object separately.

delete[]
 1. Call the destructor N times to clean up the object.
 2. Call operator delete to release space
1. operator new/operator delete, operator new[]/operator delete[] is the same as malloc/free.
2. They are only responsible for allocating space/freeing space, and will not call the object constructor, destructor to initialize or clean up the object.
3. The actual operator new and operator delete are just a layer of encapsulation of malloc and free.
Code block:
#include<stdio.h>
#include<iostream>
using namespace std;
class Array
{
public:
 Array(size_t size = 10)
  : _size(size)
 {
  cout << "构造函数:Array()" << endl;
  
 }
 ~Array()
 {
  cout << "析构函数:~Array()" << endl;
  
 }
private:
 size_t _size;
};
void Test()
{
 Array* p2 = new Array;
 Array* p3 = new Array(20);
 Array* p4 = new Array[3];//调用3次构造函数分别初始化每个对象。
 delete p2;
 delete p3;
 delete[] p4;//调用N次析构函数清理对象。
}
int main()
{
 Test();
 system("pause");
 return 0;
}


From the running results, a total of five constructors and destructors are called.
Among them, the new test[N] compiler does several things
     1. Calls the operator new[ ](size_t) function//The parameter size=sizeof(test)*N+4 here, the first four bytes store the ones that need to be constructed Times
     2. Call operator new(size) function
     3. malloc(size)
 delete[]p4 also does something similar
     1. Take the number of times the destructor is called from the first four bytes of p4
     2. Call the destructor N times (late created early release)



Locate New Expressions
placement new/delete function
concept :  initializes an object in allocated raw memory, it differs from other versions of new in that it does not allocate memory. Instead, it takes a pointer to allocated but unconstructed memory and initializes an object in that memory. In effect, positioning new expressions allows us to construct an object at a specific, preallocated memory address.

Form:
  new (place_address) type
  new (place_address) type (initializer-list) //It can be regarded as calling the constructor at place_address to initialize the object Return value: place_address where place_address must be a pointer, and initializer-list provides (maybe empty) initializer list to use when constructing newly allocated objects.
 
    


How to mock implement new/delete new[]/delete[]


Code block:
#include<stdio.h>
#include<iostream>
using namespace std;
class A
{
public:
	A(int a = 2)		//在new重定位时候使用初始化列表了,所以这里的2就无效
		:_a(a)
	{
		cout << _a << "次构造-->A()" << endl;
	}
	
	~A()
	{
		cout << "~A()" << endl;
	}
private:
	int _a;
};


void Test()
{
	//分配1个A类型空间
	A *pa = (A *)malloc(sizeof(A));
	new(pa)A(666);   //调用构造函数
	pa->~A();      //调用析构函数
	free(pa);

	//分配N个A类型的空间
	int N;
	cout << "请输入你要构造A类型空间的个数:";
	cin >> N ;
	A* pb = (A *)malloc(sizeof(A)*N+4);//多余四个字节存放N
	*(int*)pb = N;                    //解引用pb指针
	for (int i = 0; i < N; i++)       //调用N次
	{
		new(pb + i) A(i);         //重定位new并调用构造函数
	}
	for (int i = 0; i < N; i++)       //调用N次析构函数
	{
		(pb + i)->~A();
	}
	free(pb);
}
int main()
{
	Test();
	system("pause");
	return 0;
}



The above is probably my understanding of dynamic memory when I was learning C++. If there is something wrong, please criticize and correct me.


Guess you like

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