前言:
- 如果你在new表达式中使用[],
- 必须在相应的delete表达式中也使用[]
- 如果你在new表达式中不使用[],
- 一定不要在相应的delete表达式中使用[]
注意:
- 最好尽量不要对数组形式做typedef动作,
- C++标准库中含有string vector等templates
- 可将数组的需求降至几乎为零。
#include <QCoreApplication>
#include <iostream>
using namespace std;
class obj
{
public:
obj()
{
cout << "obj()\n";
}
~obj()
{
cout << "~obj()\n";
}
};
typedef obj objArray[5];
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
obj* pObj = new obj[5];
delete pObj;
cout << "%%%%%%%%%%%%%%%%%%%%%\n";
obj* pObj2 = new obj[5];
delete[] pObj2;
cout << "%%%%%%%%%%%%%%%%%%%%%\n";
obj* pObj3 = new objArray;
delete pObj3;
cout << "%%%%%%%%%%%%%%%%%%%%%\n";
obj* pObj4 = new objArray;
delete[] pObj4;
cout << "%%%%%%%%%%%%%%%%%%%%%\n";
return a.exec();
}
/*****
内容选自:
effectivre c++
改善程序与设计的55个具体做法
*****/
newdelete.JPG
网友评论