2015-12-03 49 views
-1
class foo{ 
    vector<foo*>* queue; 
    vector<int> pos; 
    foo(vector<foo*>* queue, vector<int> pos){ 
     this->queue=queue; 
     this->pos=pos; 
    } 
public: 
    foo(vector<foo*>* queue){ 
     this->queue=queue; 
    } 
    void init(){ 
     vector<int> posNew = pos; 
     //Create Binary Tree Children of the state FOO 
     posNew.push_back(/* An Additional Value*/) 
     foo newFoo(queue, posNew); 
     queue->push_back(&newFoo); 
    }//Here the variables newFoo and posNew are out of scope so they are deleted even from the queue 
} 

class bar{ 
    vector<foo*> queue; //Assume that queue has a root node added to it. 
    bar(){ 
     for(unsigned int i=0; i<queue.size();i++){ 
      queue[i]->init();// Somewhere along when the third element is calculated the value overflows since I assume the object are deleted 
     } 
    } 
} 

我正在尝试使用带队列的BFS搜索来解决问题。但是我无法让队列工作,因为我创建的对象子对象超出了范围。任何帮助,将不胜感激。如何访问超出范围的变量?

编辑: 在我的实际代码中,我有麻烦,因为当对象超出范围它显示我这些内存分配。 enter image description here

这个绿色部分是根节点的位置,红色部分是子节点的期望数据应该是的位置,但现在它被删除。

+0

为什么你需要'init()'?把东西移动到ctor('foo(vector *)')。 – GingerPlusPlus

+0

在'bar'的构造函数中,'queue'将是空的(即没有要迭代的元素)。 – crashmstr

+0

@crashmstr我们假设队列已经为二叉树添加了一个根节点。 – shadoweye14

回答

3

变量queuefoo指针的向量,而不是foo对象。但在init()中,您声明newFoofoo对象并将其推入队列中。 newFoo是函数init()的局部变量,所以当函数完成执行时,newFoo丢失。

你可以声明newFoo作为指针,并为它分配内存,就像

foo *newFoo = new foo(queue, posNew); 

,并在您的队列推newFoo

+0

啊我的坏处是,我实际上正在使用'&newFoo'运算符而不是最初将它声明为一个指针。这是否一样? – shadoweye14

+0

不是。 'newFoo'仍然是一个局部变量,在init()完成后它将会丢失。所以'&newFoo'会指向一些垃圾值。 – 0605002

+0

啊!然而,在真正的代码,因为我有'foo *'多个参数'它给了我一个'unsigned int'参数这个错误。任何猜测为什么? http://puu.sh/lI8ia/8d6f91f18a.png – shadoweye14

1

还有的“超出范围”两层含义:

  1. 通过函数调用,你跳转到标识符的词法范围之外的计划的一部分。该对象存在,但不能直接命名。间接(指针或引用)可能能够到达对象。

  2. 对于具有自动生命周期的对象,当到达作用域的末尾时,该对象被销毁。此点之后无法访问该对象,因为它不再存在。

正如0605002所暗示的,以避免例#2的一个方法是使用比自动其他寿命 - 他的回答显示动态寿命的一个例子,但静态寿命也是可能的,和数据成员也有寿命那超越了单个函数调用。

对于您的队列,由智能指针(std::unique_ptrstd::shared_ptr)管理的动态生存期将是一个不错的选择。