[問題] Dynamic Memory Allocation
關於 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指向的位置到底有什麼關係呢?
謝謝!!
--
我寧以頃刻短暫的繁華,換取千年無盡的落寞。
歡迎大家上我的“部落格”:http://coldstar.5d6d.com/forum-2-1.html
※ 編輯: WGL 來自: 140.112.241.120 (01/12 10:27)
※ WGL:轉錄至看板 NTUEE113HW 01/12 10:28
→
01/12 10:29, , 1F
01/12 10:29, 1F
→
01/12 10:30, , 2F
01/12 10:30, 2F
→
01/12 10:30, , 3F
01/12 10:30, 3F
→
01/12 10:31, , 4F
01/12 10:31, 4F
→
01/12 10:31, , 5F
01/12 10:31, 5F
→
01/12 10:33, , 6F
01/12 10:33, 6F
→
01/12 10:34, , 7F
01/12 10:34, 7F
→
01/12 10:34, , 8F
01/12 10:34, 8F
→
01/12 10:35, , 9F
01/12 10:35, 9F
→
01/12 10:35, , 10F
01/12 10:35, 10F
→
01/12 10:35, , 11F
01/12 10:35, 11F
→
01/12 10:36, , 12F
01/12 10:36, 12F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):