[关闭]
@kezhen 2015-07-15T08:20:46.000000Z 字数 1251 阅读 8377

C语言中的 new 和 delete 的使用

new delete


1. 基本数据类型的动态分配

new和delete已经完全包含maloc和free的功能,并且更强大、方便和安全。使用动态分配内存时不能忘记释放内存,不要忘记出错处理!下面先看new和delete的基本使用方法。


  1. #inclued <iostream>
  2. using namespace std;
  3. int main ( )
  4. {
  5. //基本数据类型
  6. int *i = new int; //没有初始值
  7. int *j = new int(100); //初始值为100
  8. float *f = new float(3.1415f); //初始值为3.14159
  9. cout << " i = " << *i << endl;
  10. cout << " j = " << *j << endl;
  11. cout << " f = " << *f << endl;
  12. //数组
  13. int *iArr = new int[3];
  14. for (int i=0; i<3; i++) {
  15. iArr[i] = (i+1)*10;
  16. cout << i << ": " << iArr[i] << endl;
  17. }
  18. //释放内存
  19. delete i;
  20. delete j;
  21. delete f;
  22. delete []iArr; //注意数组的删除方法
  23. return 0;
  24. }

new和delete的基本使用


2. 内存分配时的出错处理

一般有两种处理方法,一是根据指针是否为空来判断,一是用例外出错处理所抛出的“bad_alloc”来处理。

  1. #include <iostream>
  2. #include <new>
  3. using namespace std;
  4. int main ( )
  5. {
  6. //判断指针是否为NULL
  7. double *arr = new double[100000];
  8. if (!arr) {
  9. cout << "内存分配出错!" << endl;
  10. return 1;
  11. }
  12. delete []arr;
  13. //例外出错处理
  14. try {
  15. double *p = new double[100000];
  16. delete []p;
  17. } catch (bad_alloc xa) {
  18. cout << "内存分配出错!" << endl;
  19. return 1;
  20. }
  21. //强制例外时不抛出错误,这时必须要判断指针
  22. double *ptr = new(nothrow) double[100000];
  23. if (!ptr) {
  24. cout << "内存分配出错!" << endl;
  25. return 1;
  26. }
  27. delete []ptr;
  28. cout << "内存分配成功!" << endl;
  29. return 0;
  30. }

3. 用new产生类的实例

  1. #include <iostream>
  2. using namespace std;
  3. class classA {
  4. int x;
  5. public:
  6. classA(int x) { this->x = x; }
  7. int getX() { return x; }
  8. };
  9. int main ( )
  10. {
  11. classA *p = new classA(200); //调用构造函数
  12. if (!p) {
  13. cout << "内存分配出错!" << endl;
  14. return 1;
  15. }
  16. cout << "x = " << p->getX() << endl;
  17. delete p; //调用析构函数
  18. return 0;
  19. }

new产生类的实例

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注