1. 程式人生 > >C++ 類的解構函式

C++ 類的解構函式

很多部落格已經就解構函式作了非常詳細的討論,我在這篇部落格中僅僅對發生異常時解構函式的行為做討論。

一、解構函式基礎

二、程式發生異常時解構函式的行為

在C++中,對資源應該使用類來管理,在建構函式中獲得資源,在解構函式中釋放資源。但是,當程式發生異常時(呼叫exit、丟擲異常),解構函式是否能被正常的呼叫?答案是否定的。

1、呼叫exit()函式

觀察如下程式碼


#include <iostream>
using namespace std;
class A{
public:
    A(){
        cout<<"建構函式"<<endl;
}
    ~A
(){ cout<<"解構函式"<<endl; } }; void quit(){ exit(-1); } void exec(){ throw std::runtime_error("test"); } int main() { A a; quit(); return 0; }

它的輸出為:


建構函式

Process finished with exit code 255

可以看到,在main函式之前呼叫exit(),解構函式是不會被呼叫的,這樣就會造成資源釋放失敗。

2、程式丟擲異常

觀察如下程式碼


#include <iostream>
using namespace std; class A{ public: A(){ cout<<"建構函式"<<endl; } ~A(){ cout<<"解構函式"<<endl; } }; void quit(){ exit(-1); } void exec(){ throw std::runtime_error("test"); } int main() { A a; exec(); return 0; }  

它的輸出為:


建構函式
terminate called after throwing an instance of 
'std::runtime_error' what(): test Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
同樣可知,解構函式並未被呼叫。