c++ - delete right child makes parent left pointer point to nullptr -
thank checking question, have basic question on operator "delete", seems can automatically change pointer value nullptr. let me give example this:
template <typename t> void tree<t>::remove(const unsigned& index, treenode<t>*& tree) { if(tree == nullptr) { std::cerr << "remove: can't find target" << std::endl; } else if(index < tree->index) { remove(index, tree->left); } else if(index > tree->index) { remove(index, tree->right); } else if(index == tree->index) { if(tree->degree() == 2) { tree->index = findmin(tree->right)->index; tree->value = findmin(tree->right)->value; remove(tree->index, tree->right); } else { auto oldnode = tree; tree = (tree->left != nullptr) ? tree->left: tree->right; delete oldnode; // oldnode = nullptr; } } }
the code above classic searching tree remove algorithm. if current tree has 2 nodes root (with key equals 3 example) , right child (with key equals 4 example), when remove node 4, call remove twice , go line:
delete oldnode;
and line delete "oldnode", should 4 right now. far knowledge, delete operator free memory address(the address same value of oldnode), means tells os address available again. suppose when print out value of root's right pointer(root->right), should address. when print out 0. question when root->right changed?
hope explain question clearly. may stupid question, let me known if make confusion.
i think seeing use of pointer after delete undefined behavior (until c++14).
for c++14: indirection through pointer became invalid in manner , passing deallocation function (double-delete) undefined behavior. other use implementation-defined.
undefined behavior allows implementation whatever wants pointer after delete (even change value).
it looks implementation sets value of pointer nullptr in delete.