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
原文链接: https://www.cnblogs.com/LPworld/p/12902045.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/197426
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!