cleanup.html
来自「矩阵算法库newmat10.tar.gz的帮助文件」· HTML 代码 · 共 71 行
HTML
71 行
<HTML><HEAD><TITLE>Newmat09 - cleanup after an exception</TITLE></HEAD><BODY><H2>Cleanup after an exception</H2><A HREF="nonlin.html"> next</A> - <A HREF="nonlin.html"> skip</A> - <A HREF="refer.html"> up</A> - <A HREF="index.html"> start</A><P>This section is about the simulated exceptions used in newmat. It is irrelevantif you are using the exceptions built into a compiler or have set thedisable-exceptions option.<P>The simulated exception mechanisms in newmat are based on the C functions setjmpand longjmp. These functions do not call destructors so can lead togarbage being left on the heap. (I refer to memory allocated by <I>new</I> asheap memory). For example, when you call<PRE> Matrix A(20,30);</PRE>a small amount of space is used on the stack containing the row andcolumn dimensions of the matrix and 600 doubles are allocated on theheap for the actual values of the matrix. At the end of the block inwhich A is declared, the destructor for A is called and the 600doubles are freed. The locations on the stack are freed as part of thenormal operations of the stack. If you leave the block using a longjmpcommand those 600 doubles will not be freed and will occupy space untilthe program terminates.<P>To overcome this problem newmat keeps a list of all the currentlydeclared matrices and its exception mechanism will return heap memorywhen you do a Throw and Catch.<P>However it will not return heap memory from objects from other packages.<P>If you want the mechanism to work with another class you will have to dofour things:<OL><LI>derive your class from class Janitor defined in except.h;<LI>define a function <TT>void CleanUp()</TT> in that class to return all heapmemory;<LI>include the following lines in the class definition<PRE> public: void* operator new(size_t size) { do_not_link=true; void* t = ::operator new(size); return t; } void operator delete(void* t) { ::operator delete(t); }</PRE><LI>be sure to include a copy constructor in you class definition, thatis, something like<PRE> X(const X&);</PRE></OL>Note that the function <TT>CleanUp()</TT> does somewhat the same duties asthe destructor. However <TT>CleanUp()</TT> has to do the <I>cleaning</I>for the class youare working with and also the classes it is derived from. So it willoften be wrong to use exactly the same code for both <TT>CleanUp()</TT> andthe destructor or to define your destructor as a call to <TT>CleanUp()</TT>.<P><A HREF="nonlin.html"> next</A> - <A HREF="nonlin.html"> skip</A> - <A HREF="refer.html"> up</A> - <A HREF="index.html"> start</A><P></BODY></HTML>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?