[已解決] Dynamic Memory Allocation
※ [本文轉錄自 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指向的位置到底有什麼關係呢?
謝謝!!
--
→
01/12 13:15, , 1F
01/12 13:15, 1F
→
01/12 13:15, , 2F
01/12 13:15, 2F
→
01/12 13:16, , 3F
01/12 13:16, 3F
推
01/12 13:22, , 4F
01/12 13:22, 4F
推
01/12 13:56, , 5F
01/12 13:56, 5F
→
01/12 13:57, , 6F
01/12 13:57, 6F
→
01/12 13:58, , 7F
01/12 13:58, 7F
→
01/12 13:58, , 8F
01/12 13:58, 8F
→
01/12 13:58, , 9F
01/12 13:58, 9F
→
01/12 13:59, , 10F
01/12 13:59, 10F
→
01/12 14:01, , 11F
01/12 14:01, 11F
→
01/12 14:02, , 12F
01/12 14:02, 12F
推
01/12 14:07, , 13F
01/12 14:07, 13F
※ 編輯: WGL 來自: 140.112.241.120 (01/12 14:09)
→
01/12 14:07, , 14F
01/12 14:07, 14F