在C++中,new操作主要是分為一下三個版本:[來自cplusplus.com]
首先,如果要求你new一個int,你會覺得 so easy。直接
int *p = new int(5);
int *p = new int;
new操作實際上執行了3個步驟: 在堆上分配一塊內存,調用構造函數(對於簡單類型,則省略了第二步),以及返回指針。<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPjwvcD4KPHA+PGJyPgo8L3A+CjxwPjxzdHJvbmc+vdPPwsDgo6y4tNTT0ru146OszqrPwsPmtcTA4G5ld9K7uPa21M/zo6w8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+Y2xhc3MgQTwvc3Ryb25nPjwvcD4KPHA+PHN0cm9uZz57PC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPnByaXZhdGU6IGludCBhOzwvc3Ryb25nPjwvcD4KPHA+PHN0cm9uZz5wdWJsaWM6IEEoaW50IF9hKTphKF9hKSB7ICAgfTs8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+fTs8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+QSAqcGEgPSBuZXcgQTsgLy+07c7zo6xBsqLDu9PQxKzIz7m51Oy6r8r9o6jM4s3iu7DBy6Oho6k8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+QSAqcGEgPSBuZXcgQSgzKTsgINXi0ru+5M/gtbHT2ta00NDBy8/Cw+a1xMj90NC0+sLro7o8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+PGJyPgo8L3N0cm9uZz48L3A+CjxwPjxzdHJvbmc+QSAqcGEgPSAoQSopbWFsbG9jKHNpemVvZihBKSk7PC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPnBhLT5BOjpBKDMpOzwvc3Ryb25nPjwvcD4KPHA+PHN0cm9uZz5yZXR1cm4gcGE7PC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPjxicj4KPC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPrChxbajrNX9usPTodakwcvJz8PmtcTI/bj2sr3W6KGjPC9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udPD0ru49m5ld7LZ1/e3+7XEveG5+8C0tffTw7jDuq/K/aOsxMfDtL7Nz+C1sdPa1Nq4w8TatObJz9a00NC21NOmwODQzbXEubnU7Lqvyv0uPC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPjxicj4KPC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPsnPyva0+sLrtcTWtNDQveG5+6O6PC9zdHJvbmc+PC9wPgo8cD48c3Ryb25nPjxpbWcgc3JjPQ=="http://www.2cto.com/uploadfile/Collfiles/20140430/20140430090904471.jpg" alt="">
可以很清楚的看到,new (pa2) A; 該行代碼並沒有分配空間,因為它的內存地址與pa2是完全一致的。
pa3只是分配內存,並沒有創建構造函數,也就沒有調用構造函數,輸出了一個空行~~
Note:
STL庫中的new與delete在底層都是通過malloc和free來實現的。區別就是,malloc不會自動調用內存分配失敗函數。