c++ - 返回时对象的字段是随机的
问题描述
我有一个类节点,其中包含字段
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
解决方案
此 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);
}
}
推荐阅读
- asp.net - Bootstrap asp.net 使用 Multiview 显示移动视图
- android - 用于图像过滤器的 Opencv vs Opengl
- git - 如何在 TortoiseGit 中填写默认提交消息?
- mysql - 汇合的 JDBC-Sink Examples.table 不存在
- django - 抛出异常时 Gunicorn 工作人员重新启动
- c++ - qt图表等轴(轴应该是正方形而不是矩形)
- ubuntu-14.04 - gstreamer 配置错误 Ubuntu
- c# - 在实体框架中以列表形式返回选定列时出现问题
- laravel - 无法在本地使用 Laravel 重置密码
- android - 程序类型已经存在:com.loopj.android.http.AsyncHttpClient$3