C++ 一般會(huì)在構(gòu)造函數(shù)里分配資源,在析構(gòu)函數(shù)里釋放資源。但當(dāng)程序/函數(shù)不正常退出時(shí),C++ 不能保證析構(gòu)函數(shù)會(huì)被調(diào)用,這時(shí),可以利用異常,在程序/函數(shù)需要退出時(shí),扔出異常,在異常處理里退出程序/函數(shù),這樣可以使在函數(shù)調(diào)用堆棧上構(gòu)造的對(duì)象正確析構(gòu)。
示例代碼(摘自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;
}