我有一个图形对象,我想为此创建一个析构函数。然而,我并不完全适应递归,我有点迷失在我自己的数据结构中。我将展示所涉及的类和我的析构函数的开始。
class Graph {
private :
Graph* parent;
vector<Graph> child;
Board tab;
bool seen;
public :
Graph(const Board&);
Graph(const Board&, Graph*);
~Graph();
...
};
class Board {
private :
int** tab;
int nbline;
int nbcolumn;
Position emptyspot;
public :
Board();
Board(int, int, Play&);
Board(int, int);
Board(const Board&);
Board(int, int, ifstream&);
~Board();
...
};Position类只有2个int (行和列)。委员会破坏者工程:
Board::~Board()
{
for(int i = 0; i < this->nbline; i++) {
delete tab[i];
}
delete tab;
}正如您所猜测的,我想销毁图中的一个节点,以及以下所有节点。
这是我的乞丐:
Graph::~Graph() {
while(!child.empty()) {
for(vector<Graph>::iterator itr = child.begin; itr != child.end; ++itr) {
delete child[itr];
}
}
}这样我就进入了我所有的分支,递归的,对吗?当我找到一个叶(向量为空)-如果破坏一切,会发生什么在向量的父母?
我不知道父母是否会将自己设置为NULL (我不这么认为),并且父向量内存空间不会被取消分配,这样就不会满足条件child.empty(),对吗?
- Can I call `vector.erase()` in the root-node where I start deleting, in order to destroy everything recursively instead of doing the for-loop ?
发布于 2015-04-23 11:58:50
您的析构函数由于许多原因是不正确的。
child成员可能应该是vector<Graph*>,这样您就可以实际地对它们进行delete。Graph有任何子级,则循环是无限的,因为您从不更改child向量的大小。child[itr]不是如何得到与迭代器对应的Graph*,而是*itr。begin和end是成员函数,因此需要调用它们。children,不是吗?正确的循环是:
for (vector<Graph*>::iterator itr = children.begin(); itr != children.end(); ++itr) {
delete *itr; // this will recursively call Graph::~Graph()
// on the children, and then free their memory
}或者,在C++11中,我们简单地定义:
std::vector<std::unique_ptr<Graph>> children;这样我们就可以处理内存清理了。
https://stackoverflow.com/questions/29822657
复制相似问题