作者WGL (飛揚寒星)
看板NTUEE113HW
標題[問題] Dynamic Memory Allocation
時間Tue Jan 12 10:28:02 2010
※ [本文轉錄自 C_and_CPP 看板]
作者: WGL (飛揚寒星) 看板: C_and_CPP
標題: [問題] Dynamic Memory Allocation
時間: Tue Jan 12 10:25:32 2010
關於 delete [] 的問題,曾有同學提出:如果指針不再指向原來的位置,那麼
delete[]會有何效果?
於是,我設計了下面的code:
#include <iostream>
using namespace std;
class Count
{
public:
Count(int=0);
~Count();
int x;
};
Count::Count(int value) : x(value)
{
}
Count::~Count()
{
cout<<"\nDestructor for Count "<<x<<endl;
}
int main(){
Count *cptr = new Count [20];
for(int i=0;i<20;i++)
cptr[i].x=i;
cptr+=
11;
cout<<"\nNow cptr is at Count "<<cptr->x<<endl;
delete [] cptr;
system("pause");
return 0;
}
注意指針是指向第11個element。執行結果:
Now cptr is at Count 11
Destructor for Count
1330118735
Destructor for Count 19
Destructor for Count 18
Destructor for Count 17
Destructor for Count 16
Destructor for Count 15
Destructor for Count 14
Destructor for Count 13
Destructor for Count 12
Destructor for Count 11
可是如果把11改成1,結果如下:
Now cptr is at Count 1
這樣就結束了!
請問,究竟delete[] call destrucor 的範圍和pointer指向的位置到底有什麼關係呢?
謝謝!!
--
1F:→ tomap41017:以解決的解法是??? 01/12 13:15
2F:→ tomap41017:剛compile的結果跟你差不多 01/12 13:15
3F:→ tomap41017:推測delete []的方式是刪掉array的元素個 01/12 13:16
4F:推 tomap41017:看到C++板上的回答了,感謝!! 01/12 13:22
5F:推 fu3mo6:它的compile結果是結束了嗎?應該是卡住吧?執行完不會錯誤? 01/12 13:56
6F:→ WGL:不會錯誤 01/12 13:57
7F:→ WGL:我試過如果cptr--才會錯誤 01/12 13:58
8F:→ fu3mo6:我記得用陣列寫法寫的是const pointer,這樣+-雖然不會錯誤 01/12 13:58
9F:→ fu3mo6:但是刪除的時候會錯 01/12 13:58
10F:→ fu3mo6:啊啊我說的不是不能compile,是指無法執行到底 01/12 13:59
11F:→ WGL:要看用哪一種compiler,會不會錯要看運氣XD 01/12 14:01
12F:→ WGL:cptr--compile也會過但是會錯誤因為這樣讀到的element數很奇怪 01/12 14:02
13F:推 fu3mo6:運氣..我用VC++的,試了好多數字,似乎是+幾就會有幾-1次 01/12 14:07
※ 編輯: WGL 來自: 140.112.241.120 (01/12 14:09)
14F:→ fu3mo6:的destructor,而刪掉的是幾號卻很謎 01/12 14:07