gpt4 book ai didi

c++ - 将指针设置为 nullptr 会影响指向同一地址的其他指针吗?

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:58 30 4
gpt4 key购买 nike

考虑以下函数,如果节点没有子节点,它会从二叉搜索树中删除该节点:

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 setting todel->parent->left to nullptr, I'm just as well setting todel to nullptr.

这是不正确的。 todeltodel->parent->left 是不同的指针变量;将一个设置为 nullptr 不会影响另一个。

所以您没有删除 nullptr(这将是安全的并且是空操作)。

关于c++ - 将指针设置为 nullptr 会影响指向同一地址的其他指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34162130/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com