C ++ nullptr检测

时间:2015-11-11 16:03:35

标签: c++ pointers

我有以下代码。我不明白为什么在B.GetNum()中调用第一个条件。如何确保在main中删除我的B类没有尝试使用已删除的变量?

class A
{
public:
    A(int num) : m_num(num) {}
    int GetNum() { return m_num; }

private:
    int m_num;
};

class B
{
public:
    B(A* a_) : a(a_) {}
    int GetNum()
    {
        if (a != nullptr)
        {
            return a->GetNum(); // Why does this branch get called?
        }
        else
        {
            return -1;
        }
    }

private:
    A* a;
};

int _tmain(int argc, _TCHAR* argv[])
{
    A* a = new A(5);
    B b = B(a);
    delete a;
    a = nullptr;

    int result = b.GetNum();

    return 0;
}

3 个答案:

答案 0 :(得分:6)

您遇到的问题是在b中创建main()时复制指针。当您在a中更改main()时,它对b中存储的指针没有影响。

这是std::weak_ptr的完美用例。您可以B获取weak_ptr,然后在GetNum中检查指针是否仍然存在。

答案 1 :(得分:1)

您有两个不同的a。语句a = nullptr;仅影响main中的指针。 b内的指针是一个副本,包含旧值(现在无效)。

GetNum()中使用它会导致未定义的行为,并且任何都可能发生。

答案 2 :(得分:1)

因为您将A*值复制到了您的类中 - 它永远不会更改,但是当您删除原始分配值时,指针指向垃圾位置。