当我们需要为类对象动态分配存储空间时,我们应该使用 C++语言提供的 new 与 new[] 操作符,而不要使用 C语言提供的 malloc() 函数。
虽然 malloc() 函数具有分配存储空间的功能,但是这些函数除了分配存储空间外,不会调用类的构造函数。而 C++语言提供的 new 和 new[] 操作符则不会如此,使用它们为对象分配存储空间的同时,它们也会调用相应的构造函数。
操作符 delete 和 delete[] 在释放对象存储空间的同时也会调用析构函数,而 free() 函数则不会调用析构函数。
下面来看一个最简单的例子
new 的返回值就是对象的指针
new 的时候可以设置初值 int *p=new int (12);
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *p=new int (12);
//int *p= new int ;
//*p=12;
printf("%d\n",*p);
delete p;
return 0;

}
12
new 申请多个对象
用[]指定对象个数
如果new 的时候用了[] 那么delete 的时候也要用[]
#include <stdio.h>
#include <stdlib.h>
#include <string>



int main()
{
int NUM=1024;
int *p=new int [NUM];

for (int i=0;i<NUM;i++)
{
p[i]=i*i;
printf("%d%s%d\n",i,"p[i]的值",p[i]);

}


delete [] p;
return 0;

}
new 一个struct C 经典写法
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

struct Student{

int age;
char name[128];

};

int main()
{

Student *s=new Student;


s->age=33;

strcpy(s->name,"lg");


printf("%s%s%s%d%s\n","我的名字是","罗干","我今年",s->age,"岁了");
delete s;



s=NULL;

return 0;

}
new 一个class c++经典版本
#include<iostream>
#include <string>
using namespace std;

class Student{
public :
int age;
string name;

};

int main()
{

Student *s=new Student;

cout<<"delete 之前 s="<<s<<"\n"<<endl;
s->age=33;

s->name="lg";

cout<<"my name is "<< s->name<<" and my age is "<<s->age<<endl;

delete s;

cout<<"delete 之后 s="<<s<<"\n"<<endl;

s=NULL;

cout<<"s=NULL 之后 s="<<s<<"\n"<<endl;
return 0;

}

用new 申请内存,必须用delete 释放
用new[] 申请内存,必须用delete[] 释放
用完之时,及时释放

和free 一样delete 之后指针所指向的内存不在可用,应该置指针为空p=NULL;