C++之new和delete探究

相关博文:C++之new再探究

一.C语言中分配堆上的空间,不会调用构造和析构:

在这里插入图片描述
  上例代码编译会报错!
附上例代码:

//小问学编程
#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;
}

二.C++中

在这里插入图片描述
附上例代码:

//小问学编程
#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;
}

普通的基本数据类型也可以用new和delete,但仅仅是分配内存空间:
在这里插入图片描述
附上例代码:

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

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

	return 0;
}

注意:

  1.当申请一个堆上的对象时,使用new和delete,不能用malloc和free替换。
  2.C语言中在堆上申请数组:
在这里插入图片描述
  3.C++中在堆上申请数组:new[ ]分配数组,delete[ ]释放数组空间,一定要配套使用(特别是申请对象数组时)。
在这里插入图片描述
例:
在这里插入图片描述
  4.vs编译器会在new[ ]申请对象数组时, 在堆开始的前4个字节写入当前数组的长度,用于记录delete[ ]释放时,析构调用的次数。

猜你喜欢

转载自blog.csdn.net/weixin_43297891/article/details/113809487