静态成员回收内存并从异常中恢复
这是我的作业问题
创建一个具有自己的运算符 new 的类。该操作员应 分配 5 个对象,第 5 个对象“内存不足”并抛出异常 例外。还添加一个静态成员函数来回收 this 记忆。现在创建一个带有 try 块和 catch 子句的 main () 调用内存恢复例程。将它们放入 while 循环中 演示从异常中恢复并继续执行。
现在我不想要这个程序了,但我对这个问题感到困惑。我可以处理新的运算符重载,但根据要求我应该创建一个静态成员“release()”。如果我必须在捕获中恢复,我该如何恢复?我的意思是我应该删除什么对象。 或者我的release()原型是错误的?
编辑:
另外,如果我必须删除,我可以删除 5 个对象中的哪一个?事实上,删除任何对象都是不正确的。我看不到恢复的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您需要类中的静态地址列表之类的东西。每当调用 new 时,您都会将内存块的地址存储在该列表中。然后在您的释放方法中,您将遍历静态列表并释放内存并抛出异常。
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.
这是一个奇怪的任务。如果我理解正确的话,您必须将在
operator new
中创建的对象的地址存储在release()
函数可以找到它们的地方。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 therelease()
-function can find them.我对这个问题的解释是,类中 new 运算符的实现应该跟踪获取的内存,以便您的release方法(我会使用您相同的签名),可以回收记忆。
该方法用于一些分代垃圾收集器,其中在每一代期间从池中获取内存,并且一旦该代的执行完成,单个调用将释放所有内存,避免碎片和管理空闲列表(分配器)的成本可以在池内提供增加的地址,释放器只是忽略池中的数据)请注意,这种特定类型的池可能是高效的,但其使用仅限于 POD 类型。
My interpretation of the question is that the implementation of the
new
operator in your class should track the acquired memory, so that yourrelease
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.
静态成员应该有分配、释放和回收方法。
The static member should have an allocate a release and reclaim methods.