考虑以下函数,如果节点没有子节点,它会从二叉搜索树中删除该节点:
void erase_no_children(node* todel)
{
//...
if (todel->parent->left == todel) //if todel is left child
todel->parent->left = nullptr;
if (todel->parent->right == todel) //if todel is right child
todel->parent->right = nullptr;
delete todel;
}
因为 todel->parent->left == todel
这意味着通过将 todel->parent->left
设置为 nullptr
,我同样将 todel
设置为 nullptr
。编译器一点也不提示。
问题:这样做安全吗?它会泄漏吗?还是未定义的行为?
最佳答案
Since
todel->parent->left == todel
that means that by settingtodel->parent->left
tonullptr
, I'm just as well settingtodel
tonullptr
.
这是不正确的。 todel
和todel->parent->left
是不同的指针变量;将一个设置为 nullptr
不会影响另一个。
所以您没有删除 nullptr
(这将是安全的并且是空操作)。
关于c++ - 将指针设置为 nullptr 会影响指向同一地址的其他指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34162130/