8.3重学C++之【内存分布模型-new操作符】

#include<iostream>
using namespace std;


/*
    1.3 new操作符
        利用new在堆区创建数据时,会返回该数据对应的指针
        new出来的堆区数据,手动释放用delete
*/


int * func(){
  int * p = new int(10);
  return p;
}


void test_1(){
    int * p = func();
    cout << *p << endl;
    cout << *p << endl;
    cout << *p << endl;
    delete p; // 手动释放堆区变量
    //cout << *p << endl;
    //cout << *p << endl;
}


void test_2(){ // 在堆区利用new开辟数组
    int * arr = new int[10];
    for (int i=0; i<10; i++){
        arr[i] = i+100;
    }
    for (int i=0; i<10; i++){
        cout << arr[i] << endl;
    }
    delete[] arr; // 手动释放堆区数组
}


int main(){
    test_1();
    test_2();
    return 0;
}

posted @ 2021-03-12 13:09  yub4by  阅读(22)  评论(0编辑  收藏  举报