c++ - 分配和删除指针

标签 c++ memory pointers multidimensional-array

好的,这是上下文。我已经连续一天没睡了,正在研究传说中的 8 谜题。我的启发式方法和 A_star 算法都已失效。项目规范要求我们使用三个不同的启发式值来解决它。我可以单独解决这三个问题中的任何一个,但是当我连续解决它们时,我得到了一个荒谬的循环,并且它永远找不到正确的后继状态。

相信我的问题出在我的指针上。我有一个类 State,如下定义,它有一个 int** 数组和一个指向 State(其父级)的指针。

编辑:我必须使用项目规范定义的 int**,否则我很乐意使用指针。

State   (int **bd, State* prnt);
State   (const State& other);
~State  ();

然后我这样声明它们:

State::State(int **bd, State* prnt) {

// allocate the board
board = new int*[3];
for (int i = 0; i < 3; i++) {
    board[i] = new int[3];
}

// fill in the board
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        board[i][j] = bd[i][j];
        //board[i][j] = 
    }
}

// set the parent
parent = prnt;

}

State::State(const State& other) {
// allocate the board
board = new int*[3];
for (int i = 0; i < 3; i++) {
    board[i] = new int[3];

State::~State() {
//std::cout << "Deconstructing " << this << endl;
for (int i = 0; i < 3; i++)
    delete board[i];
delete [] board;
delete parent;
parent = other.parent;

}

State::~State() {
//std::cout << "Deconstructing " << this << endl;
for (int i = 0; i < 3; i++)
    delete board[i];
delete [] board;
delete parent;

}

State& State::operator=(const State &rhs) {
if (&rhs == this) {
    return *this;
}

for (int i = 0; i < 3; i++) {
    delete board[i];
}
delete [] board;

// allocate the board
board = new int*[3];
for (int i = 0; i < 3; i++) {
    board[i] = new int[3];
}

// fill in the board
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        //board[i][j] = rhs.board[i][j];
        board[i][j] = rhs.getIntAtCoor(j, i);
    }
}

//delete parent;
// set the parent
parent = rhs.parent;

// set g
g = rhs.g;
f = rhs.f;
hType = rhs.hType;

return *this;

}

我没有给出确切的声明——其中一些很简单,比如 int = int。我只是不太明白。我觉得要么是我的删除父级是错误的,要么是我的parent = other.parent是错误的(或者两者都是)。

感谢您的时间和帮助,

泰勒

最佳答案

升级您的代码风格可能会迫使错误消失。换句话说newdelete容易出错,当存在更好的替代方案时应该避免。

对于细胞的管理,请考虑:

  • std::shared_ptr : 可用于作废 delete来电
  • std::vector可用于避免 newdelete来电
    请注意,您应该像std::vector<int> board( 3 * 3 )一样使用它和board.at( x + y * 3 ) .
  • 最重要的是,只需使用静态数组 int board[3][3] 。根本没有分配。

此外,子州并不拥有其父州。恰恰相反。所以子状态不应该删除它们的父状态。您仍然可以安全地保留父指针,但请确保在允许父指针超出范围(删除或以其他方式)之前清理子指针。所有这些清理和删除根本不需要涉及新的。您的State类看起来足够小,如果它们按值复制并不重要。在这种情况下,只需让家长使用 std::vector<State> m_children编译器会处理剩下的事情。

关于c++ - 分配和删除指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931392/

相关文章:

pointers - 什么时候返回指向结构的指针是个好主意?

c - 在 C 中记录不同的数据类型

memory - 每个 CUDA 线程的本地内存量

python - 为什么 'VIRT'小于顶部的 'RES'

C- 指针、数组和结构之间的交互

c++ - 基于 for 循环迭代几个元组的范围的简明表示法是什么

c++ - 即使 nm 报告存在符号,运行时也会出现符号查找错误

c++ - 如何使用 Mysql++ 将 C++ 变量传递给 C++ 的 Insert

c++ - 使函数返回具有不同属性的东西

c# - 从另一个应用程序更改应用程序的变量