我試圖實現shared_ptr的簡化版本。但在編譯期間,編譯器彈出使用未聲明的標識符的錯誤。但是,我確實聲明瞭變量。爲什麼在派生類中找不到基類成員C++
有人能幫我找出原因嗎? 在此先感謝。
的代碼如下:
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_;
};
'這個 - > ref_count_' –
。不是調試器,而是編譯器。 – Jarod42