C++之new再探究

相关博文:C++之new和delete探究

一.C和C语言申请内存

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

//小问学编程
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
    
    
	//一.申请一个变量内存
	//1.1 C语言中
	int* pCNum=(int*)malloc(sizeof(int));
	free(pCNum);
	//1.2 C++中
	int* pCppNum=new int;
	delete pCppNum;

	//二.申请一段内存
	//2.1 C语言中
	int* pcArray=(int*)malloc(sizeof(int)*3);
	free(pcArray);
	//2.2 C++中
	int* pcppArry=new int[3];
	delete[] pcppArry;

	//三.申请并初始化
	//3.1 C语言中
	int* pAlloc=(int*)calloc(sizeof(int),3);
	if(pAlloc==nullptr)
		return 0;
	cout<<pAlloc[0]<<pAlloc[1]<<pAlloc[2]<<endl;
	free(pAlloc);
	//3.2 C++中——单个数据初始化()
	int* pNum=new int(100);
	cout<<*pNum<<endl;
	delete pNum;
	pNum=nullptr;
	//3.2 C++中——多个数据初始化{}
	int* pArray=new int[3]{
    
    1,2,3};
	cout<<pArray[0]<<pArray[1]<<pArray[2]<<endl;
	delete[] pArray;
	pArray=nullptr;

	return 0;
}

二.memory操作

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

//小问学编程
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<assert.h>
#include<cstring>
using namespace std;
int main()
{
    
    
	//四.内存池:允许我们在申请的内存上再做申请操作
	char* Memory = new char[1024];
	assert(Memory);
	int* pInt = new(Memory + 0)int[3]{
    
    1,2,3};//12字节存储整数
	assert(pInt);
	char* pChar = new(Memory + 12)char[20]{
    
     "白日依山尽!" };
	assert(pChar);
	cout << pInt[0] << pInt[1] << pInt[2] << endl;
	cout << ((int*)Memory)[0] << ((int*)Memory)[1] << ((int*)Memory)[2] << endl;

	cout << pChar << endl;
	cout << Memory + 12 << endl;

	delete[] Memory;
	Memory = nullptr;
	
	return 0;
}

三.在栈上和堆上返回值区别

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

#include<iostream>
using namespace std;

int fun1()
{
    
    
    int* x=new int(3);
    return *x;
}

int fun2()
{
    
    
    int x=3;
    return x;
}

int main()
{
    
    
    cout<<fun1()<<endl;
    cout<<fun2()<<endl;
}

猜你喜欢

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