【发布时间】:2020-10-08 09:11:10
【问题描述】:
如你所见,从我的输出结果来看,this的地址在执行过程中发生了变化,我想我可以利用指针比较来实现一个树系统,而不需要里面有一个子列表节点和我希望能够比较节点列表中每个元素的父节点以获取更多功能。但它的主要问题是指针地址更改,任何人都可以帮助我了解我缺少什么。
struct Nodo{
Nodo* parent=0;
const char* identity;
Component* component;
Nodo()=default;
Nodo(const char* uid){
identity=uid;
}
Nodo(Nodo* ptr,const char* uid){
parent=ptr;
identity=uid;
std::cout << "\n Address given to " << uid << " " << ptr <<std::endl;
}
void Add(const char* uid,std::vector<Nodo>& objects){
std::cout << "\n Add call in " << identity << " address sent "<< this <<std::endl;
objects.emplace_back(Nodo(this,uid));
}
void GrapthUI(std::vector<Nodo>& nodes){
ImGui::PushID(this);
if(ImGui::TreeNode(identity)){
ImGui::TreePop();
ImGui::Indent();
for(int indx=0; indx<nodes.size(); indx++){
if(&nodes[indx]!=this){
if(nodes[indx].parent==this){
nodes[indx].GrapthUI(nodes);
}
}
}
ImGui::Unindent();
}
ImGui::PopID();
}
}
std::vector<Nodo> node;
Main(){//in c++ file.
node.emplace_back(Nodo("root"));
node[0].Add("Airplane",node);
node[0].Add("Ball",node);
node[1].Add("Car",node);
}
输出:
Add call in [ root ] address sent 0C8FCF88
Address given to [ Airplane ] 0C8FCF88
Add call in [ root ] address sent 0C920C68
Address given to [ Ball ] 0C920C68
Add call in [ Airplane ] address sent 0C916DE4
Address given to [ Car ] 0C916DE4
我希望 Airplane 和 Ball 的父指针具有与 Root 相同的地址 [0C8FCF88]但它是不同的。我在这里看到了与此类似的同名帖子,但它对我没有帮助,也不完全涉及我的问题。
【问题讨论】:
-
您是否考虑到
std::vector可以在其增长时重新定位其成员? -
vector 在重新分配内存时使所有迭代器失效
-
不相关,但是只要你有一个节点同时满足这两个要求,GraphtUI 中的递归调用就会导致无限递归。
-
你能给我一个会导致这种情况的案例吗?我打算从单个 node[0] -(root) 节点调用 GraphUI。但可能还有其他我遗漏的案例。
标签: c++ memory-management