1. 程式人生 > >C++中幾種變數宣告的比較

C++中幾種變數宣告的比較

只有打好基礎才能寫出高質量的程式,只有搞清楚了變數到底是建立在棧上的,還是建立在堆上才能有效避免記憶體洩漏。

看這個例子:

#include <stdio.h>
class test
{
public:
    test(){printf("constructor/n");}
    test(int a){printf("aconstructor/n");}
    ~test(){printf("destructor/n");}
};

int main()
{
    test a;         // 1
    test *b;       // 2
    test c();      // 3
    test d(1);    // 4
    test *e = new test();  // 5
    return 0; 
}

輸出
1:
constructor
destructor
棧上區域性變數

2:
無輸出
BSS段

3:
無輸出
編譯器警告: 僅僅是變數定義?

4:
aconstructor
destructor
仍然是區域性變數,棧上自動處理

5:
constructor
堆上分配,未呼叫析構,記憶體洩漏!