0

Сделал вот такой абстрактный класс, который должен наследовать любой класс с подсчетом ссылок :

    template<class T>
    class ReferenceCounter
    {
    public:

        ReferenceCounter();
        ~ReferenceCounter();

        void addRef();
        void release();

        uint32 getCountReferences() const;

    protected:
        int32* pCountReferences;

        virtual void destroyObject() = 0;
        virtual void shallowCopy(const T& rhs) = 0;
    };

    template<class T>
    inline ReferenceCounter<T>::ReferenceCounter() 
    {
        pCountReferences = new int32;
        *pCountReferences = 1;
    }

    template<class T>
    inline ReferenceCounter<T>::~ReferenceCounter() 
    {
        if(pCountReferences != NULL && *pCountReferences == 0)
        {
            delete pCountReferences;
            pCountReferences = NULL;
        }
    }

    template<class T>
    inline void ReferenceCounter<T>::addRef()
    {
        debug_assert((*pCountReferences) >= 0, "Incorrect value of count references");
        ++(*pCountReferences);
    }

    template<class T>
    inline void ReferenceCounter<T>::release()
    {
        debug_assert((*pCountReferences) > 0, "Incorrect value of count references");
        (*pCountReferences)--;

        if(pCountReferences != NULL && *pCountReferences == 0)
        {
            destroyObject();
        }
    }

    template<class T>
    inline uint32 ReferenceCounter<T>::getCountReferences() const
    {
        return *pCountReferences;
    }

Вот класс умного указателя :

    template<class T>
    class SmartPtr
    {
    public:
        SmartPtr();
        SmartPtr(T* pInst);
        SmartPtr(const SmartPtr<T>& rhs);
        ~SmartPtr();

        void operator = (const SmartPtr<T>& rhs);
        T* operator -> () const;
        T* getData() const;

        bool isNULL() const;

    private:
        T* pInst;
    };

    template<class T>
    SmartPtr<T>::SmartPtr() : pInst(NULL) {}

    template<class T>
    SmartPtr<T>::SmartPtr(T* pInst) : pInst(pInst) {}

    template<class T>
    SmartPtr<T>::~SmartPtr() 
    {
        if(pInst != NULL)
        {
            pInst->release();
        }
    }

    template<class T>
    SmartPtr<T>::SmartPtr(const SmartPtr<T>& rhs)
    {
        this->pInst = rhs.pInst;
        if(pInst != NULL)
        {
            pInst->addRef();
        }
    }

    template<class T>
    void SmartPtr<T>::operator= (const SmartPtr<T>& rhs)
    {
        this->pInst = rhs.pInst;
        if(pInst != NULL)
        {
            pInst->addRef();
        }
    }

    template<class T>
    T* SmartPtr<T>::operator->() const
    {
        return pInst;
    }

    template<class T>
    T* SmartPtr<T>::getData() const
    {
        return pInst;
    }

    template<class T>
    bool SmartPtr<T>::isNULL() const
    {
        return pInst == NULL;
    }

Код где тестировал это :

#include <iostream>
#include "ReferenceCounter.h"
#include "SmartPtr.h"

using namespace std;
using namespace OGE::memory;

class B;

class A : public ReferenceCounter<A>
{
public:
    A();
    A(const A& rhs);
    ~A();

    SmartPtr<B> getB();
    void operator = (const A& rhs);

private:
    void destroyObject();
    void shallowCopy(const A& rhs);
};

class B : public ReferenceCounter<B>
{
private:
    void destroyObject() {} ;
    void shallowCopy(const B& rhs) {};
};

A::A()
{
    cout << "Create object" << endl;
}

A::A(const A& rhs)
{
    shallowCopy(rhs);
    addRef();
    cout << "copy constructor " << endl;
}

A::~A()
{
    release();
}

void A::destroyObject()
{
    cout << "destroy" << endl;
}

void A::shallowCopy(const A& rhs)
{
    this->pCountReferences = rhs.pCountReferences;
}

void A::operator = (const A& rhs)
{
    shallowCopy(rhs);
    addRef();
    cout << "operator = " << endl;
}

SmartPtr<B> A::getB()
{
    return SmartPtr<B>(new B());
}

SmartPtr<A> getA()
{
    SmartPtr<A> a(new A());
    return a;
}

int main()
{
    getA();
    return 0;
}

Это код отлично работает, все разрушается. А вот тут, где используется struct forward declaration не вызывается конструктор копировщик из-за чего о корректности нельзя говорить.

int main()
{
   A a;
   a.getB();
}

Помогите разобраться в чем проблема ?

1 ответ 1

1

Думаю Вам стоит изучить сначала как сделаны имеющиеся хорошие варианты - boost::shared_ptr<T>, std::shared_ptr<T>, CComPtr<T> - и тогда все вопросы отпадут (если уж их использовать совсем никак нельзя и надо писать что-то свое).

2
  • Проблема была вот тут : SmartPtr<B> A::getB() { return SmartPtr<B>(new B()); } Вот такой код заработал : SmartPtr<B> A::getB() { SmartPtr<B> b(new B()); return b; } Видимо проблема была в RVO ? 6 янв 2013 в 12:11
  • 1
    Да, скорее всего RVO.
    – ivan.ukr
    6 янв 2013 в 13:30

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.