指向同一对象的两个指针

时间:2015-08-17 10:44:22

标签: c++ memory-management

我有两个指向同一个对象的指针,我需要正确删除它们(删除每个对象A和内部对象B)。但问题是共享对象在删除后仍然分配了内存:一个悬空指针。如何在不使用智能指针的情况下避免此类问题。

     class A
        {

        public:
            class B
            {
            private:
                A* m_x;
                A* m_y;
            public:
                B(A* x, A* y);
                ~B();
            };

            B* m_b;
            A(){};
            void Join(A* other);
            ~A();
        };

        void A::Join(A* person)
        {
           this->m_b= new A::B(this, person);
           person->m_b= this->m_b;
        }

        A::~A()
        {
          if (m_b)
          {
            delete m_b;
            m_b= NULL;
          }
        }

        ...

        A aa = new A();
        A cc = new A();
        aa->Join(cc);
        delete aa

        // here I have a problem in deleting the *m_b because it's deleted by the first A 
        delete cc;

1 个答案:

答案 0 :(得分:1)

如果没有智能指针,您可以做的最好的事情就是在销毁时将aacc分开。但是,不要这样做,使用std::shared_ptr并忘记类似的头痛:

// annul pointers to this shared object
B::detach() {
    if (m_x) m_x->m_b = NULL;
    if (m_y) m_y->m_b = NULL;
}

A::~A() {
    // use a temporary pointer, because B::detach will annul the pointers here
    if (m_b) {
        B* tmp = m_b;
        tmp->detach();
        delete tmp;
    }
}

此类代码非常不好。它是不可维护的,类是耦合的,我甚至不确定它是否正确。