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
[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
相关文章推荐
- C++线性代数库Armadillo
- 【读书笔记:C++ primer plus 第六版 中文版】第2章:开始学习C++
- C++构造函数中抛出的异常
- Effective C++ 条款6
- C++ 与 C
- C++语言基础 例程 字符串类
- C++语言基础 例程 函数模板
- C++语言基础 例程 函数重载
- C++语言基础 例程 有默认参数的函数
- C++语言基础 例程 内置函数
- 3D dungeon
- C++语言基础 例程 C++中的输入和输出
- C++语言基础 例程 C++的数据类型和运算符
- Effective C++ 条款5
- C语言宏定义
- assert用法,原理,改编(C++)
- Elements of Modern C++ Style
- C++ stderr/stdout 重定向到文件
- Effective c++ 3/e item 15 疑問解惑
- OpenCV+C++ 视频图片相互转换