首页 > 解决方案 > 返回时对象的字段是随机的

问题描述

我有一个类节点,其中包含字段

class Node{
public:
    int lowestCost;
    std::list<Node> children;

    Node* leastCost();
    Node();
    Node(int low)
}
Node(int low){
  this->lowestCost = low;
}

还有一个功能

Node* Node::leastCost() {

    if(children.empty()){
        //this works fine
        return this;
    }
    else{
      //This doesn't
      Node* lowboi = (&children.front());
        for(Node n : children) {
            if ((*lowboi).lowestCost > n.lowestCost) {
                    lowboi= (&n);
            }
        }
        return (*lowboi).leastCost();
    }
}

当我尝试访问由函数返回的节点*的字段时,例如

Node* startNode = new Node();
current = startNode;

current.children.emplace_back(Node(1));
current.children.emplace_back(Node(1));
current.children.emplace_back(Node(3));
current.children.emplace_back(Node(4));

`This is just an example`

current = (*startNode).leastCost();



cout<<(*current).children.size();

计数是一些大数字,例如 4363000057,但最多可以是 4

标签: c++

解决方案


此 for 循环在堆栈上创建节点的副本:

    for(Node n : children) {
        if ((*lowboi).lowestCost > n.lowestCost) {
                lowboi= (&n);
        }
    }

因此,您的lowboi变量在循环迭代结束时成为一个悬空指针。如果您进行n引用,这应该可以解决问题(假设列表节点本身在指针的生命周期内仍然有效):

    for(Node& n : children) {
        if ((*lowboi).lowestCost > n.lowestCost) {
                lowboi= (&n);
        }
    }

推荐阅读