1. 程式人生 > >C++ 宣告一個變數 和 New 一個空間的區別

C++ 宣告一個變數 和 New 一個空間的區別

C++ 中宣告一個變數,這個變數具有一定的作用域和生命週期。

作用域:    就是一個變數被引用的範圍。

生命週期:這個變數可以被引用的時間段,不同生命週期的變數,在程式記憶體中的分佈位置不同,一個程式記憶體分為:程式碼區、全域性資料區、堆區、棧區,不同的記憶體區域對應不同的生命週期;

如果沒有當前函式以外的指標指向它,則在當前函式結束時,會將當前變數析構;如果有函式以外的指標指向它,則不會被析構;

如果用New 的方式宣告變數,則當前空間會被儲存至程式執行結束;

#include <iostream>

using namespace std;

struct Node{
    int value =1;
    Node *next;
}n1;
int main(){
    Node *s  = &n1
; cout<<s->value<<endl; return 0; }
#include <iostream>

using namespace std;

struct Node{
    int value =1;
    Node *next;
}n1;
int main(){
    Node *s = new Node;
cout<<s->value<<endl;
return 0;
}

new 相當於重新定義了一個結果體物件,並把地址傳給 s;

#include <iostream>

using namespace std;

struct Node{
    int value ;
    Node *next;
}n1,n2,*start;

int main(){
    n1.value = 1;
    n2.value = 2;
    start = &n1;
    n1.next = &n2;

    for(int i=0;i<2;i++){
        cout<<start->value<<endl;
        start = start->next;
    }
return 0;
}

#include <iostream>

using namespace std;

struct Node{
    int value ;
    Node *next;
}*start;

int main(){
   Node *n1 = new Node;
   Node *n2 = new Node;
   n1->value = 1;
   n2->value = 2;
   n1->next = n2;
   start = n1;

    for(int i=0;i<2;i++){
        cout<<start->value<<endl;
        start = start->next;
    }
return 0;
}