2015-04-23 79 views
0

我有一个图形对象,我想为此创建一个析构函数。然而,我并没有真正舒适的递归,而且我有点迷失在我自己的数据结构中。我将展示涉及的类和我的析构函数的开始。析构函数,图形和递归性

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(); 
     ... 
}; 

位置类只有2个int(行和列)。 董事会析构函数作品:

Board::~Board() 
{ 
    for(int i = 0; i < this->nbline; i++) { 
     delete tab[i]; 
    } 
    delete tab; 
} 

正如你猜到了,我想破坏我图的节点,并且所有的以下节点。

这里是我的beggining:

Graph::~Graph() {   
    while(!child.empty()) {     
     for(vector<Graph>::iterator itr = child.begin; itr != child.end; ++itr) { 
      delete child[itr]; 
     } 
    } 
} 

这样,我进入我的所有分支,递归,对不对?当我找到一片叶子(矢量为空)时 - 如果摧毁了所有东西,父母的矢量中会发生什么?我不知道父母是否会将自己设置为NULL(我不这么认为),并且父向量内存空间不会被未分配,因此child.empty()条件将不会被满足,对 ?

  • 如何以及何时销毁* Graph?

  • 我会冒堆栈溢出吗?

    • 我可以在我开始删除的根节点中调用vector.erase(),以便递归销毁所有内容而不是执行for-loop?
+0

是小孩矢量或矢量?你有'矢量',但你打电话给删除,所以我很困惑。 – NathanOliver

+0

这是我的一个错误,它应该是矢量,我将不得不更改构造函数^^' – Csi

回答

2

您的析构函数由于诸多原因而不正确。

  1. child成员大概应该是vector<Graph*>,这样你实际上可以delete他们。
  2. 如果你的Graph有任何孩子,你的循环是无限的,因为你永远不会改变child矢量的大小
  3. child[itr]是不是你如何得到Graph*对应的迭代器,*itr是。
  4. beginend是成员函数,所以需要调用它们。
  5. 该成员应该可能被命名为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; 

,使内存清理将是我们处理。

+0

@Csi:如果您没有C++ 11功能,请选中[Boost Smart Pointers](http:/ /www.boost.org/doc/libs/release/libs/smart_ptr/smart_ptr.htm)。它们基本上都是用C++ 98的手段实现的。 – DevSolar

+0

@DevSolar我没有权利使用Boost; _;老师是非常老派:'( – Csi

+0

@DevSolar Thx哥们:-)我在人们的建议之后通过修改回答了这个话题,现在是否正确? – Csi