Static member reclaiming memory and recovering from an exception [closed]

怎甘沉沦 提交于 2019-12-11 10:06:07

问题


This is my assignment question

Create a class with its own operator new. This operator should allocate 5 objects, and on 5th 'run out of memory' and throw an exception. Also add a static member function that reclaims this memory. Now create a main () with try block and catch clause that calls the memory-restoration routine. Put these inside a while loop to demonstrate recovering from an exception and continuing execution.

Now I don't want the program, but I am confused with this question. I can handle new operator overloading, but as asked I should create a static member "release()". And if I have to recover in catch, how do I recover? I mean what object should I delete. Or my prototype for release() is wrong?

Edit:
Also if I have to delete, which of the 5 objects can I delete? And deleting any object would in fact be incorrect. I see no way of recovery.


回答1:


Sounds like you would need something like a static list of addresses in your class. Whenever new is called you store the address of the memory block in that list. Then in your release method you go through the static list and free the memory plus throw the exception.




回答2:


This is a strange assignment. If I understand this right, you'd have to store the addresses of the objects created inside your operator new somewhere the release()-function can find them.




回答3:


My interpretation of the question is that the implementation of the new operator in your class should track the acquired memory, so that your release method (I would use your same signature), can reclaim the memory.

That approach is used in some generational garbage collectors where during each generation memory is acquired from a pool, and once the execution for the generation completes a single call will release all the memory, avoiding fragmentation and the cost of managing the free list (the allocator can provide increasing addresses inside the pool, the deallocator just ignores the data in the pool) Note that this particular type of pool can be efficient, but its use is limited to POD types.




回答4:


The static member should have an allocate a release and reclaim methods.

struct AllocatorPool
{
     char*  allocate(size_t size);
     void   deallocate(char* ptr);

     void   reclaimPool();

     // Other stuff to handle memory management.
};

class T
{
      static  AllocatorPool    memoryForOjectsOfTypeT;


     // You new method here that gets memory from `memoryForOjectsOfTypeT`
};


来源:https://stackoverflow.com/questions/7833196/static-member-reclaiming-memory-and-recovering-from-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!