我有班級甲板和遊戲卡。甲板對象必須有指針的動態分配的陣列,以遊戲牌對象:釋放指針數組的內存?
PlayingCard** _playing_cards;
初始化此陣列中,甲板的構造,並建立()函數被稱爲:
Deck::Deck(int size)
{
_total_playing_cards = size;
_deal_next = 0;
build();
}
void Deck::build()
{
_playing_cards = new PlayingCard*[_total_playing_cards];
for(int i = 1; i <= _total_playing_cards; ++i)
{
_playing_cards[i-1] = new PlayingCard(i % 13, i % 4);
}
}
釋放與分配的存儲器「新」是在析構函數處理:
Deck::~Deck()
{
for(int i = 0; i < _total_playing_cards; ++i)
{
delete[] _playing_cards[i];
}
delete[] _playing_cards;
}
我然後有一個單獨的文件,deck_test.cpp,其中有一個主()來簡單地構建和破壞一個甲板對象:
int main()
{
Deck deck(52);
deck.~Deck();
return 0;
}
編譯沒有問題,但是在調試,Visual Studio的報告時 「在播放Cards.exe在0x5ab159da(msvcr100d.dll)未處理的異常:0000005:訪問衝突讀取位置0xfeeefee2」在查看調用堆棧時,問題似乎在我使用析構函數中'for'循環中的'delete []'運算符時發生。這不是從指針數組中釋放內存的正確方法嗎?
在for循環中,不會刪除沒有[]的空格,因爲您正在刪除_playing_cards [i]指向的對象和對象? – octopusgrabbus 2012-02-04 19:39:43