我实现了一个基本的智能指针类。它适用于以下类型的代码。(考虑 Base1 有一个公共构造函数)
Sptr<Base1> b(new Base1);
b->myFunc();
{
Sptr<Base1> c = b;
Sptr<Base1> d(b);
Sptr<Base1> e;
e = b;
}
但是在测试代码中它有一个受保护的构造函数(我需要它是这样的)。和代码
Sptr<Base1> sp(new Derived);
产生以下错误(注意派生):
Sptr.cpp: In instantiation of ‘my::Sptr<T>::~Sptr() [with T = Base1]’:
Sptr.cpp:254:39: required from here
Sptr.cpp:205:9: error: ‘Base1::~Base1()’ is protected
Sptr.cpp:97:17: error: within this context
问题是我必须确保通过指向 Derived 的指针而不是 Base1 进行删除。我怎样才能做到这一点?
这是类代码(剪辑以显示构造函数和析构函数以及类成员)
template <class T>
class Sptr {
private:
T* obj; // The actual object pointed by
RC* ref;// A reference object to keep track of count
public:
//declarations
template <typename T>
Sptr<T>::Sptr():obj(NULL),ref(NULL) {
//do something
std::cout<<"()\n";
ref = new RC();
ref->AddRef();
}
template <typename T>
Sptr<T>::Sptr(const Sptr &a) : obj(a.obj),ref(a.ref) {
//do something
std::cout<<"const Sptr\n";
ref->AddRef();
}
template <typename T>
Sptr<T>::~Sptr() {
//do something
if(ref->Release() == 0) {
if(obj)
delete obj;
delete ref;
}
}
template <typename T>
template <typename U>
Sptr<T>::Sptr(U* u) : obj(u),ref(NULL) {
//do something
ref = new RC();
ref->AddRef();
}
template <typename T>
template <typename U>
Sptr<T>::Sptr(const Sptr<U> &u) : obj(u.obj),ref(u.ref) {
std::cout<<"const Sptr<U>\n";
ref->AddRef();
}
编辑
析构函数不是虚拟的。这就是我必须解决的情况。下面是Base1
和Derived
类
class Base1 {
protected:
Base1() : derived_destructor_called(false) {
printf("Base1::Base1()\n");
}
private:
Base1(const Base1 &); // Disallow.
Base1 &operator=(const Base1 &); // Disallow.
protected:
~Base1() {
printf("Base1::~Base1()\n");
assert(derived_destructor_called);
}
protected:
bool derived_destructor_called;
};
class Derived : public Base1 {
friend void basic_tests_1();
private:
Derived() {}
Derived(const Derived &); // Disallow.
Derived &operator=(const Derived &); // Disallow.
public:
~Derived() {
printf("Derived::~Derived()\n");
derived_destructor_called = true;
}
int value;
};