我正在尝试实现B +树。这只是实际代码的一小部分。将对象指针传递给函数时遇到了一些问题。据我所知,在函数内创建的那些对象后来被破坏了。那么在不改变语义的情况下改进它并保持函数递归的好方法是什么呢。任何反馈都将不胜感激。
void percolate_up(IndexNode* Current, int btree_order, IndexNode* Right, IndexNode* Root)
{
if(Current->Parent == NULL)
{
IndexNode* UpperNode = new IndexNode;
UpperNode->AddChild(Current);
UpperNode->AddChild(Right);
Current->Parent = UpperNode;
Right->Parent = UpperNode; //This is defined inside an if statement
// in main yet this statement doesn't affect it
UpperNode->AddKey(Current->Keys[btree_order]);
Root = UpperNode;
}
else if(.......){
...
...
percolate_up(....);
}
}
int main(){
...
if(...){
IndexNode* RightNode = new IndexNode;
percolate_up(Current, btree_order, RightNode, Root);
//RightNode->Parent is still NULL here but Current->Parent is changed
//Also Root is unchanged, Why does this happen?
}
答案 0 :(得分:1)
使用" new"创建的所有对象函数返回后会存在。所以你应该使用它。