Research on new and delete in C++

Related blog post: C++ new research

1. Allocate space on the heap in C language, without calling construction and destruction:

Insert picture description here
  The above code compiles will report an error!
Attach example code:

//小问学编程
#include<stdlib.h>
#include<string.h>

class CStudent{
    
    
	public:
	//构造函数
	CStudent(){
    
    
		printf("CStudent()\r\n");
	};
	
	//析构函数
	~CStudent(){
    
    
		printf("~CStudent()\r\n");
	}
private:
	int m_nStuID;//学号														
};
	
int main()
{
    
    
	//栈上的对象
	//全局对象
	//堆对象
	char* pBuf=(char*)malloc(10);
	
	CStudent* pStu=(CStudent*)malloc(sizeof(CStudent));
	
	free(pStu);
	
	return 0;
}

Two. C++

Insert picture description here
Attach example code:

//小问学编程
#include<iostream>
using namespace std;

//运算符:
//1.new 分配空间,调用构造函数
//2.delete 调用析构函数,释放空间
class CStudent{
    
    
	public:
	//构造函数
	CStudent(){
    
    
		cout<<"CStudent()\r\n";
	};

	//析构函数
	~CStudent(){
    
    
		cout<<"~CStudent()\r\n";
	}
private:
	int m_nStuID;//学号
};

int main()
{
    
    
	//在堆上创建一个对象
	CStudent* pStu=new CStudent;

	if(pStu!=nullptr)
	{
    
    
		//释放对象
		delete pStu;
	}

	return 0;
}

Ordinary basic data types can also use new and delete, but only to allocate memory space:
Insert picture description here
attach example code:

//小问学编程
#include<iostream>
using namespace std;

int main()
{
    
    
	int* pN=new int;
	delete pN;

	return 0;
}

note:

  1. When applying for an object on the heap, use new and delete instead of malloc and free.
  2. Apply for an array on the heap in C language:
Insert picture description here
  3. Apply for an array on the heap in C ++: new[] allocates an array, delete[] releases the array space, and must be used in conjunction (especially when applying for an object array).
Insert picture description here
Example:
Insert picture description here
  4. The vs compiler will write the length of the current array in the first 4 bytes at the beginning of the heap when applying for an object array with new[] to record the number of destructuring calls when delete[] is released.

Guess you like

Origin blog.csdn.net/weixin_43297891/article/details/113809487