首页 > 编程语言 > 详细

【C++】关于new分配空间

时间:2020-05-16 21:16:04      阅读:47      评论:0      收藏:0      [点我收藏+]

1如果不使用new,则在函数结束时内存被回收,指针变成野指针

#include <iostream>
using namespace std;
struct Node {
    int val;
    Node *next;
    Node(int v=0,Node * n=NULL){
        val=v;
        next=n;
    }
};
Node * head;

void fun(){
    Node t(1);
    head=&t;
    cout<<"head"<<head->val<<" "<<head->next<<endl;
}

int main(){
    fun();
    cout<<"head"<<head->val<<" "<<head->next<<endl;
    return 0;
}
执行完成,耗时:0 ms
head1 0
head54732392 0x7fc624c80649

2如果使用new,则必须使用delete才能回收内存

#include <iostream>
using namespace std;
struct Node {
    int val;
    Node *next;
    Node(int v=0,Node * n=NULL){
        val=v;
        next=n;
    }
};
Node * head;

void fun(){
    head=new Node(1);
    cout<<"head"<<head->val<<" "<<head->next<<endl;
}

int main(){
    fun();
    cout<<"head"<<head->val<<" "<<head->next<<endl;
    delete head;
    return 0;
}
执行完成,耗时:4 ms
head1 0
head1 0

 

【C++】关于new分配空间

原文:https://www.cnblogs.com/LPworld/p/12902045.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!