C++ nullptr检测

lot*_*ons 1 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;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 6

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

这是std :: weak_ptr的完美用例.你可以B拿a weak_ptr然后在GetNum你可以检查指针是否仍然存在.