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;
}