class Queue{node
private:mvc
struct node{函數
string data;指針
struct node * next,*priv;對象
}內存
private:get
struct node * pthread;編譯器
}string
當我給struct node 分配一塊新內存時編譯
struct node * pnew
pnew = (struct node *)malloc(sizeof(struct node));
此時應用pnew指針就會出現段錯誤,而在編譯的時候是沒有辦法檢測出來的。
正確應用是
struct node * pnew
pnew = new node ;
緣由就在於
對象在建立的同時要自動執行構造函數,對象在消亡以前要自動執行析構函數。因爲malloc/free是庫函數而不是運算符,不在編譯器控制權限以內,不可以把執行構造函數和析構函數的任務強加於malloc/free,因此malloc僅僅是分配一塊連續內存,而string 僅僅給分配一堆指針的空間是沒有意義的,因此在應用的時候會出現段錯誤。