如何递归删除自引用类C ++

时间:2016-01-14 08:44:01

标签: c++ recursion tree heap delete-operator

我一直在搜索论坛,试图理解如何以递归方式从堆中释放所有内存但该过程尚未完成。

Game类就像一个树对象,map[2][8][8]就是它上面的数据。游戏类代表棋盘,*moves[64]是一系列儿童游戏。

我的移动生成功能添加将增量根移动到生成的移动量。

当我game.clear()删除所有孩子时,它会删除最低层的孩子,但之后会失败。我的代码出了什么问题?我的思维过程就是在游戏中调用删除,调用析构函数,在析构函数中,它递归循环遍历所有移动,直到你处于底层,然后才能恢复原状。

class Game {
    public:
    char data[2][8][8];
    int roots = 0;
    Game *moves[64];

    ~Game() {
        for (int i = 0; i < roots; i++) {
            delete moves[i];
            moves[i] = NULL;
        }
    }
    void clear() {
        for (int i = 0; i < roots; i++) {
            delete moves[i];
            moves[i] = NULL;
        }
    }
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 8; j++) {
            delete[] map[i][j];
        }
        delete[] map[i];
    }
    delete[] map;
    private:
    ....
    void make_move(int x, int y, int dx, int dy) {
        Game *move = new Game;
        for (int i = 0; i < 2; i++)
            for (int x = 0; x < 8; x++)
                for (int y = 0; y < 8; y++)
                    (*move).map[i][x][y] = map[i][x][y];
        (*move).t = t + 1;
        if(map[0][x][y] == -map[0][x + dx][y + dy])
            (*move).h = h + map[1][x + dx][y + dy];
        (*move).map[0][x + dx][y + dy] = map[0][x][y];
        (*move).map[0][x][y] = 0;
        (*move).map[1][x + dx][y + dy] = map[1][x][y];
        (*move).map[1][x][y] = 0;
        moves[roots++] = move;
    }
}


int num = 0;
int paths = 0;
void benchmark(Game &game, int depth) {
    if (depth == 0)
        return;
    game.add_moves();
    for (int i = 0; i < game.roots; i++)
        benchmark(*game.moves[i], depth - 1);
    num += game.roots;
    paths++;
}
void print_benchmark(Game &game, int depth) {
    int t1 = clock();
    benchmark(game, 1);
    int t2 = clock();
    printf("num=%d, t=%.3f, mps=%.2f, paths=%d\n", num, (t2 - t1) / (double)CLOCKS_PER_SEC, num / ((t2 - t1) / (double)CLOCKS_PER_SEC), paths);
}

int main() {
    Game game;
    Handler io;

    io.set(game, "reset");
    print_benchmark(game, 5);

    game.clear();
    cin.ignore();
    return 0;
}

0 个答案:

没有答案