[英]destructing a pointer to a dynamic 2d array in C++
作為我從學校得到的作業的一部分,我一直試圖解決這個分配/破壞問題很長一段時間,基本上我需要分配一個我設計的簡單類的二維數組指針。
class RobotsWorld{
public:
RobotsWorld(int width,int hight);
~RobotsWorld();
/**
* copy,Assign,operator=
*/
//RobotsWorld(const RobotsWorld &);
//void Assign(const RobotsWorld &);
//RobotsWorld& operator=(const RobotsWorld &);
bool addRobot(Robot & r,Point p);
bool moveRobot(Robot & r);
bool removeRobot(Robot & r);
Point getPosition(Robot r);
string toString();
Robot* getRobotInWorld(Robot & r);
/** validation functions **/
bool checkOutOfBounds(int,int);
bool isEmptySlot(int x,int y);
bool ableToMove(Robot &);
private:
Robot*** robots;
Point point;
int width,height;
};
這不是函數的完整源文件,但這些函數會導致崩潰\\內存丟失。 (是的,它必須定義為三重指針 - ***機器人)
RobotsWorld::RobotsWorld(int width,int height)
:width(width),height(height)
{
robots = new Robot**;
*robots = new Robot*[height];
for(int i = 0 ; i < height ; i++){
robots[i] = new Robot*[width];
for(int j = 0 ; j < width ; j++)
robots[i][j] = NULL;
}
}
RobotsWorld::~RobotsWorld(){
for(int i = 0 ; i < height ; i++){
delete [] robots[i];
robots[i] = NULL;
}
delete [] *robots;
delete **robots;
}
機器人類和主要沒有分配什么。 我一直試圖尋找解決方案,但即使描述這種情況也證明它本身就很困難。
您需要兩個嵌套循環來刪除二維指針數組 - 刪除單個機器人和刪除機器人行:
RobotsWorld::~RobotsWorld(){
for(int i = 0 ; i < height ; i++) {
for(int j = 0 ; j < width ; j++) {
delete robots[i][j]; // Delete each individual robot
}
delete[] robots[i]; // Delete the row of robots
}
// Finally delete the 2D array itself
delete[] robots;
}
雖然在刪除后將指針設置為NULL
通常是個好主意,但在析構函數中這樣做是浪費 CPU 周期; 我建議跳過是。
這是很多工作(我相信你可以看到)。 使用標准 C++ 庫可以幫助您通過使用合適的容器來避免所有這些工作 - 例如,
vector<vector<unique_ptr<Robot> > > robots;
現在將自動處理與管理機器人內存相關的任務。
最后一行:
delete **robots;
很可能是你的問題。 它應該是:
delete robots;
robots = new Robot**;
*robots = new Robot*[height];
不正確,你想要
robots = new Robot**[height];
我無法想象為什么有必要擁有一個T***
並且我當然無法在沒有幫助類的情況下為這樣的事情維護資源! 如果我不能使用std::vector<T>
來幫助維護,我將實現一個類似的類(嗯,這對我來說很容易:我已經實現了我自己的 C++ 標准庫版本......)。
我還沒有尋找所有的問題,但直接的 oroblem 是你new robots**
並將結果視為在robots[i]
具有更多元素。
我在這個答案中復制我的評論:
您還可以使用:
template <int WIDTH, int HEIGHT>
class RobotsWorld
{
public:
/*... functions ...*/
private:
Robot robots[WIDTH][HEIGHT];
/*... other private data ...*/
};
而且你不必關心new
/ delete
東西;-)
但是,您必須實現一些operator
以允許:
RobotsWorld<3,4> rw34;
RobotsWorld<5,6> rw56 = rw34;
if (rw56 == rw34) /*...*/;
如果您不需要允許操作如上幾行,那么template
是一個優雅的解決方案。
您想要存儲指向 Robot 的二維指針數組。 這是一個可能的初始化例程:
RobotsWorld::RobotsWorld(int width,int height)
:width(width),height(height)
{
robots = new (Robot**)[height];
for(int i = 0 ; i < height ; i++){
(*robots)[i] = new (Robot*)[width];
for(int j = 0 ; j < width ; j++)
robots[i][j] = NULL;
}
}
析構函數應該實現雙重操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.