
解構函數 (destructor) 為程式結束執行銷毀物件之用,通常編譯器會提供預設的解構函數,可是當類別成員有指標的時候,就需要寫自己的解構函數,使其進行有效的記憶體管理。
舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | Demo(int pa) { |
| 006 | std::cout << "constructor" << std::endl; |
| 007 | a_ptr = new int; |
| 008 | *a_ptr = pa; |
| 009 | } |
| 010 | |
| 011 | ~Demo() { |
| 012 | std::cout << "destructor" << std::endl; |
| 013 | delete a_ptr; |
| 014 | } |
| 015 | |
| 016 | void do_something() { |
| 017 | std::cout << *a_ptr << std::endl; |
| 018 | } |
| 019 | |
| 020 | private: |
| 021 | int *a_ptr; |
| 022 | }; |
| 023 | |
| 024 | int main(void) { |
| 025 | Demo d(2048); |
| 026 | d.do_something(); |
| 027 | |
| 028 | return 0; |
| 029 | } |
| 030 | |
| 031 | /* Kaiching Chang |
| 032 | u0915.cpp |
| 033 | 2014-02 */ |
解構函數在第 11 行,用 ~ 符號表示解構函數,裡頭用 delete 刪除指標成員
| 011 | ~Demo() { |
| 012 | std::cout << "destructor" << std::endl; |
| 013 | delete a_ptr; |
| 014 | } |
編譯執行,結果如下
| $ g++ u0915.cpp |
| $ ./a.out |
| constructor |
| 2048 |
| destructor |
| $ |
continue ...
沒有留言:
張貼留言