C++动态空间的申请
为什么C++的动态分配是new和delete?
因为malloc 函数和对应的free函数不能调用构造函数和析构函数,这破坏了空间分配、初始化的功能。所以引入了new和delete。
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version : www.zzzyk.com
// Copyright : sg131971@qq.com
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
int id;
~aa()
{
cout << "aa is completed." << endl;
}
};
int main(int argc, char **argv)
{
aa *p = new aa(9);
cout << p->id << endl;
delete p;
cout << "" << endl;
aa *q = (aa *) malloc(sizeof(aa));
cout << q->id << endl;//随机数 表明构造函数未调用
free(q);//析构函数未调用
}
运行结果:
aa is constructed.
9
aa is completed.
3018824
堆空间不伴随函数动态释放,程序员要自主管理
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : sg131971@qq.com
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
~aa()
{
cout << "aa is completed." << endl;
}
int id;
};
aa & m()
{
aa *p = new aa(9);
delete p;
return (*p);
}
int main(int argc, char **argv)
{
aa & s = m();
cout << s.id;// 结果为随机数,表明被释放
}
运行结果:
aa is constructed.
aa is completed.
4984904
函数内部的申请空间要及时释放,否则容易造成内存重复申请和内存迷失。
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : sg131971@qq.com
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
~aa()
{
cout << "aa is completed." << endl;
}
int id;
};
void p()
{
aa *s = new aa[9999];
}
int main(int argc, char **argv)
{
for (;;)
p();
return 0;
}
摘自 sg131971的学习笔记
补充:软件开发 , C++ ,