美文网首页
智能指针失效的情况

智能指针失效的情况

作者: book_02 | 来源:发表于2020-06-10 21:23 被阅读0次

    1. 智能指针的交叉引用

    1.1 正常情况输出

    #include <iostream>
    #include <memory>
    
    using namespace std;
    
    class B;
    
    class A {
    public:
        A() { cout << "A()" << endl; }
        ~A() { cout << "~A()" << endl; }
    };
    
    class B {
    public:
        B() { cout << "B()" << endl; }
        ~B() { cout << "~B()" << endl; }
    };
    
    int main()
    {
    
        {
            shared_ptr<A> pA(new A());
            shared_ptr<B> pB(new B());
        }   // 超出作用域,应当析构
    
        return 0;
    }
    

    结果

    A()
    B()
    ~B()
    ~A()
    

    1.2 交叉引用造成泄漏

    #include <iostream>
    #include <memory>
    
    using namespace std;
    
    class B;
    
    class A {
    public:
        A() { cout << "A()" << endl; }
        ~A() { cout << "~A()" << endl; }
    
        shared_ptr<B> pb;   // 智能指针指向B
    };
    
    class B {
    public:
        B() { cout << "B()" << endl; }
        ~B() { cout << "~B()" << endl; }
    
        shared_ptr<A> pa;   // 智能指针指向A
    };
    
    int main()
    {
    
        {
            shared_ptr<A> pA(new A());
            shared_ptr<B> pB(new B());
    
            pA->pb = pB;    // 给成员智能指针赋值
            pB->pa = pA;    
        }   // 超出作用域,应当析构
    
        return 0;
    }
    
    A()
    B()
    

    两个类的析构都没有执行,说明存在内存泄漏了。

    2. 解决方法

    把类成员的shared_ptr 换成 弱指针 weak_ptr

    #include <iostream>
    #include <memory>
    
    using namespace std;
    
    class B;
    
    class A {
    public:
        A() { cout << "A()" << endl; }
        ~A() { cout << "~A()" << endl; }
    
        weak_ptr<B> pb;     // 从 `shared_ptr` 换成 `weak_ptr`
    };
    
    class B {
    public:
        B() { cout << "B()" << endl; }
        ~B() { cout << "~B()" << endl; }
    
        weak_ptr<A> pa;     // 从 `shared_ptr` 换成 `weak_ptr`
    };
    
    int main()
    {
    
        {
            shared_ptr<A> pA(new A());
            shared_ptr<B> pB(new B());
    
            pA->pb = pB;
            pB->pa = pA;
        }   // 超出作用域,应当析构
    
        return 0;
    }
    

    结果

    A()
    B()
    ~B()
    ~A()
    

    正常析构,解决了内存泄漏。

    相关文章

      网友评论

          本文标题:智能指针失效的情况

          本文链接:https://www.haomeiwen.com/subject/nfrmtktx.html