在另一个 class 中删除具有受保护析构函数的对象

Deleting an object with a protected destructor in another class

我知道之前有人在这里问过这个问题: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(){

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

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()};