本文共 741 字,大约阅读时间需要 2 分钟。
Scott Meyers说:成对使用new和delete时要采取相同形式。 意思很简单, 但我们程序员应该非常小心, 尤其是在处理堆内存问题的时候。 new和delete使用不恰当, 会产生未定义的不明确行为。 比如, 如下方式就是很好的方式:
- #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;
- }
但是, 有一种隐蔽的错误, 如:
- #include <iostream>
- using namespace std;
-
- typedef int intArr[100];
-
-
-
-
-
-
-
- int main()
- {
- int *p = new intArr;
- delete p;
- p = NULL;
-
- return 0;
- }
应该采用:
- #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