C++笔记-異常處理機制(释放堆区空间)
发布日期:2021-06-30 10:41:07 浏览次数:2 分类:技术文章

本文共 2710 字,大约阅读时间需要 9 分钟。

最近都在擼Java代碼,身爲C++程序員,看到java中異常機制,非常的香,看看以前的C++項目,對異常寫的不是很多,看看公司大佬們C++代碼,對異常處理也不多。在此,我自己總結下,方便以後在C++代碼中,多用異常處理機制,使得程序健壯性有所提升。

 

此博文最關鍵的是使用智能指針,接管堆區對象,實現自動的釋放。

 

1. 編碼時的防錯方法;

2. 程序異常機制的處理方法;

3. 異常發生時内存管理方法。

 

 

編碼時的防錯:

使用斷言:assert(表達式)

          在重新運行時的錯誤。

          斷言只存在于Debug版的程序。

代碼如下:

#include 
#include
using namespace std;int myDiv(int num1, int num2) { int ret = num1 / num2; return ret;}int main(int argc, int *argv[]) { cout << myDiv(10, 0) << endl; getchar(); return 0;}

儅num2輸入0時

下面使用斷言來試試看

#include 
#include
using namespace std;int myDiv(int num1, int num2) { assert(num2 != 0); int ret = num1 / num2; return ret;}int main(int argc, int *argv[]) { cout << myDiv(10, 0) << endl; getchar(); return 0;}

num2不爲0時就往下走

從中可以看出,挺友好的。

 

 

下面是使用abort()函數或exit()函數進行編碼時的防錯。

返回錯誤標志:返回bool類型,返回int類型。

注意:abort()存在于cstdlib頭文件中

#include 
#include
using namespace std;int main(int argc, int *argv[]) { int x; int y; cout << "please input tow number: "; cin >> x >> y; if (y == 0) { cout << "error: y is 0" << endl; abort(); } else { cout << "The result is " << x / y << endl; } getchar(); getchar(); return 0;}

正常輸入:

錯誤輸入:

這裏exit()就不再演示了。

 

下面是最重要的一點:異常機制。

使用try塊,異常發生時,使用throw抛出,使用catch塊捕獲異常。

如下,正常的代碼:

#include 
#include
using namespace std;double calc(int para) { if (para < 0) { throw "error, The para < 0"; } return sqrt(para);}int main(int argc, int *argv[]) { double ret = -1.0; try { ret = calc(20); } catch (const char *e) { cout << e << endl; } cout << "The result is : " << ret << endl; getchar(); return 0;}

運行截圖如下:

儅輸入小於0的值后:

這樣通過異常機制,程序就不會崩潰了

 

這裏,對比下java,java的異常有throw,try,catch,finally。這個finally很是重要,如果有加鎖,在這個地方可以解鎖。

 

在C++中,就沒這麽好運了,沒有finally。但有些優秀的框架,比如Qt,在異常加鎖,解鎖上,都有很好的處理,在此,不再研究加鎖,和解鎖,這一塊。

 

目前考慮如下:在try中new的東西,如何去釋放!!!!

異常發生時的内存管理:

堆棧解退:如果函數因爲異常而終止,從throw到try之間所有局部變量都會自動撤銷,類對象的析構函數也會被執行。

 

如下代碼:

#include 
using namespace std;class MyClass { public: int num; MyClass(int n) { num = n; } ~MyClass() { cout << "~MyClass() called! The num is : " << num << endl; }};int main(int argc, int *argv[]) { try { MyClass m(1); MyClass *my2 = new MyClass(2); throw "error"; } catch (const char *e) { cout << e << endl; } getchar(); return 0;}

運行截圖如下:

從中可以看到那個new出來的指針並沒有被釋放。

代碼修改如下:

#include 
#include
using namespace std;class MyClass { public: int num; MyClass(int n) { num = n; } ~MyClass() { cout << "~MyClass() called! The num is : " << num << endl; }};int main(int argc, int *argv[]) { try { MyClass m(1); MyClass *my2 = new MyClass(2); unique_ptr
uniMy2Ptr(my2); //方便自動釋放 throw "error"; } catch (const char *e) { cout << e << endl; } getchar(); return 0;}

使用智能指針去接管,讓其制動釋放:

出現運行截圖如下:

 

转载地址:https://it1995.blog.csdn.net/article/details/103651284 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:OllyDbg笔记-软件逆向调试技巧
下一篇:Java工作笔记-Spring Boot中使用Mybatis操作达梦数据库

发表评论

最新留言

不错!
[***.144.177.141]2024年04月19日 05时28分45秒