如何访问超出范围的变量?

sha*_*e14 0 c++ pointers

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将BFS搜索与队列一起使用以解决问题。但是,由于我创建的对象子对象超出范围,因此无法使队列工作。任何帮助,将不胜感激。

编辑: 在我的实际代码中,我遇到了麻烦,因为当对象超出范围时,它将向我显示这些内存分配。 在此处输入图片说明

绿色部分是根节点的位置,红色部分是子节点的预期数据应该在的位置,但现在已删除。

060*_*002 5

变量queuefoo指针的向量,而不是foo对象。但是在中init(),您将声明newFoo为一个foo对象并将其推送到队列中。newFoo是function的局部变量init(),因此当函数完成执行时,newFoo将会丢失。

您可以声明newFoo为指针并为其分配内存,例如

foo *newFoo = new foo(queue, posNew);
Run Code Online (Sandbox Code Playgroud)

并推入newFoo队列。