new和delete的使用

最后更新于:2022-04-02 02:07:38

[TOC] ## 基本数据类型的动态分配
main.cpp ``` #include using namespace std; int main() { //基本数据类型 int *i1=new int; int *i2=new int(); int *i3=new int(100); float *i4=new float(1.11f); cout << "i1 = " <<*i1 << endl; cout << "i2 = " <<*i2 << endl; cout << "i3 = " <<*i3 << endl; cout << "i4 = " <<*i4 << endl; //数组 int *iArr = new int[3]; for (size_t i = 0; i < 3; i++) { iArr[i]=i; cout << i << " : " << iArr[i] << endl; } // 释放内存 delete i1; delete i2; delete i3; delete i4; delete []iArr; return 0 ; } ```

## 内存分配时的出错处理
main.cpp ``` #include using namespace std; int main() { //判断指针是否为NULL double *arr1 = new double[100000]; if (!arr1) { cout << "内存分配出错!" << endl; return 1; } delete[] arr1; // try catch try { double *arr2 = new double[100000]; delete[] arr2; } catch (const std::exception &e) { std::cerr << "内存分配出错!" << endl; return 1; } double *arr3 = new (nothrow) double[100000]; if (!arr3) { cout << "内存分配出错!" << endl; return 1; } delete[] arr3; cout << "内存分配成功!" << endl; return 0; } ```

## 用new产生类的实例
main.cpp ``` #include using namespace std; class A { public: int x; void setX(int x) { this->x = x; } int getX() { return this->x; } }; int main() { A *a = new A(); if (!a) { cout << "内存分配出错!" << endl; return 1; } a->setX(123); cout << a->getX() << endl; delete a; return 0; } ```

';