C++ 一般會在構造函數里分配資源,在析構函數里釋放資源。但當程序/函數不正常退出時,C++ 不能保證析構函數會被調用,這時,可以利用異常,在程序/函數需要退出時,扔出異常,在異常處理里退出程序/函數,這樣可以使在函數調用堆棧上構造的對象正確析構。
示例代碼(摘自advanced linux programming 4.3.2 Thread Cleanup in C++):
#include <pthread.h>
class ThreadExitException
{
public:
/* Create an exception-signaling thread exit with RETURN_VALUE. */
ThreadExitException (void* return_value)
: thread_return_value_ (return_value)
{
}
/* Actually exit the thread, using the return value provided in the constructor. */
void* DoThreadExit ()
{
pthread_exit (thread_return_value_);
}
private:
/* The return value that will be used when exiting the thread. */
void* thread_return_value_;
};
void do_some_work ()
{
while (1) {
/* Do some useful things here
*/
if (should_exit_thread_immediately ())
throw ThreadExitException (/* thread’s return value = */ NULL);
}
}
void* thread_function (void*)
{
try {
do_some_work ();
}
catch (ThreadExitException ex) {
/* Some function indicated that we should exit the thread. */
ex.DoThreadExit ();
}
return NULL;
}