zoukankan      html  css  js  c++  java
  • 【C++】关于new分配空间

    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
  • 相关阅读:
    CSP游戏 4
    CSP 交通规划
    CSP 地铁修建
    CSP 通信网络
    CSP URL映射
    CSP 权限查询
    CSP Markdown
    CSP JSON 查询
    SQL里的子查询
    SQL里的操作符
  • 原文地址:https://www.cnblogs.com/LPworld/p/12902045.html
Copyright © 2011-2022 走看看