在另一个类

时间:2017-04-21 18:35:41

标签: c++ protected

我知道此前有人问过这个问题:Delete an object with a protected destructor。但是,解决方案对我来说并不起作用。编译期间我仍然遇到错误。

我的项目也是创建一个智能指针,有些测试让我删除带有受保护的析构函数的对象(有些是虚拟的,有些则不是),这会导致编译时错误。

我真的不知道从哪里开始解决这个问题。提前谢谢!

这就是我必须做的事情:

#include <cstddef>

template<typename T> void DefaultDeleter(void *p) { delete static_cast<T*>(p); }

struct ref_counter {
    int refs;
    void *p;
    void (*d)(void *);
};

template<typename T> class Sptr { 
    public:
            Sptr(T *obj){
            c = new ref_counter;
            c->refs = 1;
            c->p = static_cast<void*>(obj);
            c->d = &DefaultDeleter<T>;
            p = p;
        }
        void reset(){
            (c->d)(c->p);
            delete c;
        }
    private:
        T *p;
        ref_counter *c;
};

class Base{
    public:
        Base(){
            atr = new int(1);
        }
    protected:
        ~Base(){
            delete atr;
        }
    private:
        int *atr;
};

int main(){
    Base b1;
    Sptr<Base> s1(&b1);
    return 0;
}

此代码导致此错误:

root@resnet-230-99:~/cs440/a3# g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:43:7: error: ‘Base::~Base()’ is protected within this context
  Base b1;
       ^~
test.cpp:35:3: note: declared protected here
   ~Base(){
   ^
test.cpp: In instantiation of ‘void DefaultDeleter(void*) [with T = Base]’:
test.cpp:17:9:   required from ‘Sptr<T>::Sptr(T*) [with T = Base]’
test.cpp:44:19:   required from here
test.cpp:3:53: error: ‘Base::~Base()’ is protected within this context
 template<typename T> void DefaultDeleter(void *p) { delete static_cast<T*>(p); }
                                                     ^~~~~~
test.cpp:35:3: note: declared protected here
   ~Base(){

1 个答案:

答案 0 :(得分:2)

问题是你的构造函数采用可以销毁的实数类型,即使基类析构函数受到保护,例如:

template<typename T>
class Sptr {
public:
    template <typename U>
    explicit Sptr(U* obj){
        c = new ref_counter;
        c->refs = 1;
        c->p = static_cast<void*>(obj);
        c->d = &DefaultDeleter<U>;
    }
// ...
};

然后,用:

class Base {
protected:
    ~Base() = default;
};

class Derived : public Base
{
public:
    ~Derived() = default;
};

你可以做

Sptr<Base> p{new Derived()};