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

标签 c++ c++11 nullptr

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

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/

相关文章:

c++ - std::vector::emplace_back 和 std::move

c++ - 不能使用 "not"、 "or"或 "plus"作为标识符?

c++ - 如何检查 c++11 std::regex_replace 是否成功?

c++ - nullptr 和指针算法

c++ - 这些是空指针,还是指向地址 0 的指针?

c++ - C++11 标准是否通过 "n2 is int&"保证 "auto n2 = const_cast<int&>(n);"?

c++ - 如何在重新绘制之前清除 QwtPlot 曲线?

c++ - 枚举唯一的无向路径的有效方法

C++ Builder nullptr 关键字 "Undefined"

c++ - 如何在至少有 1 个邻居等于 1 的数组中设置框