目录
1.利用new创建内存
1.1 创建单个变量(对象)
1.1.1格式
1.1.2代码
1.2 创建数组
1.2.1格式
1.2.2代码
2.利用delete释放内存
2.1格式
2.2 代码
new是在堆区申请一块连续的内存空间,如果申请成功,则返回内存指针,如果申请失败,则返NULL。
new申请内存空间的过程,通常称为new一个对象。与 malloc()相比:
int main()
{
int a;
int* p1 = new int;//动态创建一个int,没有初始化,随机值(0xcdcdcdcd)
int* p2 = &a;//随机值,0xcccccccc
cout << *p1 << endl;
cout << *p2 << endl;
int* p2 = new int(10);//动态创建一个int,并初始化为10
cout << *p2 << endl;
int* p3 = new int();//初始化为0
cout << *p3 << endl;
int* p4 = new int{ 200 };//动态创建一个整型,初始化为200,C++11新增加的
cout << *p4 << endl;
return 0;
}
int main()
{
//动态创建一个double
double* p1 = new double;
//动态创建一个string,并初始化为趣字节
string* p2 = new string{ "趣字节" };
//动态创建一个short,并初始化为20
short* p3 = new short(20);
cout << *p1 << "," << *p2 << "," << *p3 << endl;
return 0;
}
int main()
{
int* p = new int[10];//动态创建10个长度的int数组,随机值
for (int i = 0; i < 10; i++)
{
cout << p[i] << " ";
}
cout << endl;
int* p1 = new int[10] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//动态创建10长度的int数组,并初始化为{1,2,3,4...}
for (int i = 0; i < 10; i++)
{
cout << p1[i] << " ";
}
cout << endl;
int* p3 = new int[10] {1, 2, 3, 4, 5};//动态创建10长度的int数组
for (int i = 0; i < 10; i++)
{
cout << p3[i] << " ";
}
cout << endl;
string* p4 = new string[3]{ "我爱你","中国" };
for (int i = 0; i < 3; i++)
{
cout << p4[i] << " ";
}
cout << endl;
}
用new运算符分配的内存在使用后要及时释放以免造成内存泄漏,C++提供了delete运算符释放new出来的内存空间,并自动调用其析构函数。
int main()
{
//动态创建一个double
double* p1 = new double;
//动态创建一个string,并初始化为趣字节
string* p2 = new string{ "趣字节" };
//动态创建一个short,并初始化为20
short* p3 = new short(20);
cout << *p1 << "," << *p2 << "," << *p3 << endl;
//销毁上面三个变量
delete p1;
delete p2;
delete p3;
return 0;
}
int main()
{
int* p = new int[10];//动态创建10个长度的int数组,随机值
for (int i = 0; i < 10; i++)
{
cout << p[i] << " ";
}
cout << endl;
int* p1 = new int[10] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//动态创建10长度的int数组,并初始化为{1,2,3,4...}
for (int i = 0; i < 10; i++)
{
cout << p1[i] << " ";
}
cout << endl;
int* p3 = new int[10] {1, 2, 3, 4, 5};//动态创建10长度的int数组
for (int i = 0; i < 10; i++)
{
cout << p3[i] << " ";
}
cout << endl;
string* p4 = new string[3]{ "我爱你","中国" };
for (int i = 0; i < 3; i++)
{
cout << p4[i] << " ";
}
cout << endl;
//注意释放
//释放数组,必须加[]
//delete []p1;//注意一定要加[]
delete []p;
delete []p3;
delete []p4;
}
注:
int main()
{
int* p1 = new int[5];
//delete p1;//错误1,使用new []分配,应该使用delete []p1;
int* p2 = new int;
int* p3 = p2;
delete p2;
//delete p3;//错误2,多次delete同一段内存
int arr[5];
int* p4 = arr;
//delete p4;//错误3,delete不能释放非动态内存
int* p5 = NULL;
delete p5;//正确,delete 空指针是安全的
//delete NULL;//语法错误,这条语句没有意义
return 0;
}
delete[ ]中的方括号告诉程序,应释放整个数组,而不仅仅是指针指向的一个元素。如果使用new时,不带方括号,则使用delete时,不带方括号。如果使用new时,带方括号,则使用delete时也应带方括号。对于C++标准来说,new和delete的格式不匹配导致的后果时不确定的。
一般来说,不要用两个指针指向同一个动态创建的内存,因为这将增加错误删除同一段内存两次的可能性。