|
藍森林 http://www.lslnet.com 2006年6月6日 10:18
C++中delete?
我是一個初學者,我在windows 2000下用VC++6.0調試所學程序,為什麼用new分配內存後,用delete釋放時總出錯呢,就算是最後一行也不行,請各位指教! |
C++中delete?
你是怎麼樣做的,你申請的是不是[]? |
C++中delete?
delete的地址是不是你new的地址 |
C++中delete?
會不會中間被你又把指針值改變了. |
C++中delete?
//filename:first.cpp
// A first look at C++ program
#include <iostream.h>;
#include <ctype.h>;
class animalType
{
char breed[40]; //array of characters
public:
void getBreed(void) //Get the animal's breed name
{
cout<<"What is the breed?";
cin>;>;breed; //User types the name
}
void prBreed(void)
{
cout<<"The animal'breed is "<<breed<<'\n';
}
};
//Actral program starts here
void main(void)
{
animalType *animals[25]; //C++ doesn't need class keyboard
float *newf=new float;
float testf;
int num = 0;
char ans;
do
{ animals[num]=new animalType; //Allocate space
animals[num++]->;getBreed();
cout<<"Do you want to enter another animal(Y/N)?";
cin>;>;ans;
}
while (toupper(ans)!='N');
// Now,print each of the breeds
for (int ctr=0;ctr<num;ctr++)
{ animals[ctr]->;prBreed(); }
}
如果我想釋放animals,怎麼寫程序? |
C++中delete?
《Effective C++》
--------------------------------------------------------------------------------
條款5:對應的new和delete要採用相同的形式
下面的語句有什麼錯?
[code]string *stringarray = new string[100];
...
delete stringarray;[/code]
一切好像都井然有序——一個new對應著一個delete——然而卻隱藏著很大的錯誤:程序的運行情況將是不可預測的。至少,stringarray指向的100個string對像中的99個不會被正確地摧毀,因為他們的析構函數永遠不會被調用。
用new的時候會發生兩件事。首先,內存被分配(通過operator new 函數,詳見條款7-10和條款m8),然後,為被分配的內存調用一個或多個構造函數。用delete的時候,也有兩件事發生:首先,為將被釋放的內存調用一個或多個析構函數,然後,釋放內存(通過operator delete 函數,詳見條款8和m8)。對於 delete來說會有這樣一個重要的問題:內存中有多少個對象要被刪除?答案決定了將有多少個析構函數會被調用。
這個問題簡單來說就是:要被刪除的指針指向的是單個對象呢,還是對像數組?這只有你來告訴delete。如果你在用delete時沒用括號,delete就會認為指向的是單個對象,否則,它就會認為指向的是一個數組:
[code]string *stringptr1 = new string;
string *stringptr2 = new string[100];
...
delete stringptr1;// 刪除一個對像
delete [] stringptr2;// 刪除對像數組[/code]
如果你在stringptr1前加了"[]"會怎樣呢?答案是:那將是不可預測的;如果你沒在stringptr2前沒加上"[]"又會怎樣呢?答案也是:不可預測。而且對於象int這樣的固定類型來說,結果也是不可預測的,即使這樣的類型沒有析構函數。所以,解決這類問題的規則很簡單:如果你調用new時用了[],調用delete時也要用[]。如果調用new時沒有用[],那調用delete時也不要用[]。
在寫一個包含指針數據成員,並且提供多個構造函數的類時,牢記這一規則尤其重要。因為這樣的話,你就必須在所有初始化指針成員的構造函數里採用相同的new的形式。否則,析構函數里將採用什麼形式的delete呢?關於這一話題的進一步闡述,參見條款11。
這個規則對喜歡用typedef的人來說也很重要,因為寫typedef的程序員必須告訴別人,用new創建了一個typedef定義的類型的對象後,該用什麼形式的delete來刪除。舉例如下:
[code]typedef string addresslines[4]; //一個人的地址,共4行,每行一個string
//因為addresslines是個數組,使用new:
string *pal = new addresslines; // 注意"new addresslines"返回string*, 和
// "new string[4]"返回的一樣
delete時必須以數組形式與之對應:
delete pal;// 錯誤!
delete [] pal;// 正確[/code]
為了避免混亂,最好杜絕對數組類型用typedefs。這其實很容易,因為標準c++庫(見條款49)包含有stirng和vector模板,使用他們將會使對數組的需求減少到幾乎零。舉例來說,addresslines可以定義為一個字符串(string)的向量(vector),即addresslines可定義為vector<string>;類型。 |
C++中delete?
樓主,你的代碼中並沒有new出一個數組,而只是用一個數組來保存了多次調用new產生的指針,所以應該這樣釋放:
for(int i=0;i<num;i++)
{
delete animals[i];
} |
| |