为什么在派生类c ++

时间:2015-11-12 19:59:09

标签: c++ templates c++11 smart-pointers

我试图实现shared_ptr的简化版本。但是在编译时,编译器弹出了使用未声明标识符的错误。但是,我确实声明了变量。

有人可以帮我找出原因吗? 提前谢谢。

代码如下:

template <typename T>
class S_ptr
{
// private classes definition
private:
    template <typename T2>
    class DefaultDeleter
    {
    public:
        void operator()(T2* p) { delete p; }
    };

    class Aux
    {
        template<typename> friend class S_ptr;
    public:
        // constructor & destructor
        Aux() : ref_count_(1) {}

        virtual ~Aux() {}

        // member method
        virtual void incre() { ++ref_count_; }
        virtual void decre() = 0;
        virtual void destroy() = 0;

    protected:
        unsigned int ref_count_;  // UNDECLARED IDENTIFIER
    };

    template <typename T2, typename Deleter>
    class AuxCounter : public Aux
    {
    public:
        // constructor & destructor
        AuxCounter(T2* p, Deleter d) : ptr_(p), deleter_(d) {}

        ~AuxCounter() { decre(); }

        // member method
        void decre() override { if(--ref_count_ == 0) destroy(); } // ERROR 
        void destroy() override { deleter_(ptr_); }

        //public member
        T2* ptr_;
    private:
        Deleter deleter_;
    };
    // private class defination end

public:
    // constructor & destructor
    S_ptr(T* p) : ptr_(new T(*p))
    {
        counter_ = new AuxCounter<T, DefaultDeleter<T>>(ptr_,     DefaultDeleter<T>());
        delete p;
        p = nullptr;
    }
    template <typename T2, typename D> S_ptr(T2* p, D&& deleter) :     ptr_(new T(*p))
    {
        counter_ = new AuxCounter<T, D>(new T(*p), deleter);
        delete p;
        p = nullptr;
    }
    S_ptr(S_ptr<T>& rhs) : ptr_(rhs.ptr_), counter_(rhs.counter_) { counter_->incre(); }

    ~S_ptr() { delete counter_; }

    // assignment
    S_ptr& operator=(const S_ptr<T>& rhs)
    {
        auto temp = rhs.counter_;
    temp->incre();
    counter_->decre();
    counter_ = temp;
    ptr_ = rhs.ptr_;
    return *this;
}
// ..........

// private data member
T* ptr_;
Aux *counter_;

};

1 个答案:

答案 0 :(得分:1)

由于ref_count_是从属名称,您应该使用

this->ref_count_

Aux::ref_count_