简体   繁体   中英

C++ nullptr detection

I have the following code. I don't understand why the first conditional gets invoked in B.GetNum(). How can I ensure when a gets deleted in main that my class B does not try to use the deleted variable?

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;
}

The problem you are having is you copy the pointer when you create b in main() . When you change a in main() it has no effect on pointer stored in b .

This is a perfect use case for a std::weak_ptr . You can have B take a weak_ptr and then in GetNum you can check if the pointer still exist.

You have two different a . The statement a = nullptr; affects only the pointer inside main. The pointer inside b is a copy and contains the old value (now invalid).

Using it in GetNum() leads to undefined behavior, and anything can happen.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM