我实现了一个基本的智能指针类。它适用于以下类型的代码。 (考虑到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);
产生以下错误(注意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;
};
答案 0 :(得分:2)
如果使构造函数成为模板,则可以检测构造时传入的指针类型,并将该信息保存在智能指针中(例如,在多态删除器对象中)。这是(我相信)shared_ptr<>
如何做到的。如果传入的指针类型没有可访问的析构函数,您也可以使用SFINAE生成编译器错误。