如何通过只知道它的基指针来删除整个对象

时间:2017-06-22 15:02:46

标签: c++ inheritance release-management

我正在尝试在c ++中实现自动释放池,并且在解除分配时遇到问题。 所以我们有根类对象:

class object {
 public:
    object() {
        retainCount_ = 0;
    }
    ~object() {
        std::cout << "object " << Description() << " is dealocated" << std::endl;
    }
    /* code with retain/release here */
    int retainCount() {
        return retainCount_;
    }
    std::string Description() {
        std::stringstream ss;
        ss << this;
        return ss.str();
    }
 private:
    int retainCount_;
};

还有一些实现:

class Integer : public object {
 public:
    int i;
    Integer(int ii) : i(ii) {}
    ~Integer() {
        std::cout << "Integer " << Description() << " is dealocated" << std::endl;
    }
};

当然还有发布池类,它适用于根类指针:

class release_pool {
 public:
    void insert(object* obj) {
        pointers_.insert(obj);
    }
    void flush() {
        std::set<object*>::iterator it = pointers_.begin();
        std::set<object*>::iterator tmp;
        const int N = pointers_.size();
        for (int i = 0; i < N; i++) {
            tmp = it;
            it++;
            if ((*tmp)->retainCount() == 0 ) {
                object* obj = *tmp;
                std::cout << "delete obj: " << obj->Description() << std::endl;
                pointers_.erase(tmp);
                delete obj;
            }
        }
    }
 private:
    std::set<object*> pointers_;
};

main.cpp测试代码:

int main () {
    release_pool pool;

    Integer* obj = new Integer(5);
    pool.insert(obj);
    std::cout << "before flush: " << obj->i << "\n";

    pool.flush();

    std::cout << "after flush: " << obj->i << "\n";    
    return 0;
}

构建完成后,我接下来:

before flush: 5
delete obj: 0x7f9a84c025d0
object 0x7f9a84c025d0 is dealocated
after flush: 5

最后:调用root-class的析构函数,但不调用Integer的析构函数。因此,我们泄漏了内存,它被分配给Integer对象。你有什么想法来解决它吗?我如何删除整个对象,而不是删除它的根部。

1 个答案:

答案 0 :(得分:2)

您需要使对象析构函数为虚拟。