您的位置:首页 > 编程语言 > C语言/C++

Effective C++条款16:成对使用new和delete时要采取相同形式

2015-06-21 11:04 453 查看
Scott Meyers说:成对使用new和delete时要采取相同形式。 意思很简单, 但我们程序员应该非常小心, 尤其是在处理堆内存问题的时候。 new和delete使用不恰当, 会产生未定义的不明确行为。 比如, 如下方式就是很好的方式:

[cpp] view
plaincopy

#include <iostream>

using namespace std;



int main()

{

int *p = new int;

delete p; // 此时不能有[]

p = NULL;



p = new int[4];

delete []p; // 此时必须有[]

p = NULL;



return 0;

}

但是, 有一种隐蔽的错误, 如:

[cpp] view
plaincopy

#include <iostream>

using namespace std;



typedef int intArr[100];







// ...







int main()

{

int *p = new intArr;

delete p; //错误, 会产生不明确的未定义行为

p = NULL;



return 0;

}

应该采用:

[cpp] view
plaincopy

#include <iostream>

using namespace std;



typedef int intArr[100];







// ...







int main()

{

int *p = new intArr;

delete []p; // 必须用[]

p = NULL;



return 0;

}

为了避免第二个程序中的错误, Scott Meyers建议最好不要对数组采用typedef定义。

链接:http://blog.csdn.net/stpeace/article/details/46574847
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: