回收内存(内存恢复例程)

时间:2014-12-02 13:32:24

标签: c++ memory-management delete-operator

我这里有一些代码。我在这里要做的是,我想使用重载运算符new分配10个对象,并且在11日"内存耗尽"并抛出一个例外。我添加了一个静态成员函数,它回收为第10个对象分配的内存,以便我可以使用该地址并将其分配给新对象。

我还在学习c ++的过程,所以你们的评论家们都非常感激。

帮我评估一下我的课程。我不知道如何收回内存,然后使用地址分配下一个新对象。

谢谢。

P.S。我怎样才能使用'这个'在重载运算符new?

#include <iostream>
#include <cstdlib>
using namespace std;

int count=0;

class RunOutOfMemory : public exception{

    public:
    const char * Message(){
        return "Run out of memory!";
    }

};

class ObjectAllocation{

    public:
    ObjectAllocation(){
        cout << count << "Object Allocated at " << &this[count] << endl;
    }

    //Operator new overloaded
    void * operator new(){
        count++;
        if(count>=11){
            throw RunOutOfMemory();
        }
    }

    //Reclaim memory allocated for 10th instance 
    //so that a new object can be instantiate on its memory address
    static void reclaim(){
        //delete?
    }
};

int main(int argc, char * argv[]){
    ObjectAllocation * objAlloc;
    int counter=0;
    cout << &objAlloc << endl;

    while(counter<=20){
        counter++;
        try{
            objAlloc = new ObjectAllocation();
            cout << &objAlloc[counter] << endl;
        }catch(RunOutOfMemory room){
            cout << room.Message() << endl;
            objAlloc.reclaim();
        }
    }
}

0 个答案:

没有答案
相关问题