日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ exception

發(fā)布時(shí)間:2025/3/21 c/c++ 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ exception 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

今天看書發(fā)現(xiàn)拋出異常,有幾種不同的寫法,查找資料找出了不同之處。

C++對(duì)異常對(duì)象的傳遞有按值傳遞、按引用傳遞和按指針傳遞三種方式。

上表格:

throw 方式的不同導(dǎo)致catch 時(shí)形參類型不同。

參考:

http://www.parashift.com/c++-faq-lite/what-to-catch.html

http://www.parashift.com/c++-faq-lite/catch-by-ptr-in-mfc.html

In fact, you have all the flexibility that you have in declaring function parameters, and the rules for whether a particular exception matches (i.e., will be caught by) a particular catch clause are almost exactly the same as the rules for parameter compatibility when calling a function.

Given all this flexibility, how do you decide what to catch? Simple: unless there's a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer.

通常,如果沒有特殊原因,通過引用傳遞;避免傳值,因?yàn)榘粗祩鬟f會(huì)引發(fā)拷貝,而此拷貝可能會(huì)和原來拋出的異常不同;只有在特殊情況下才使用指針傳遞。

對(duì)于自帶的exception和自己寫的exception的比較:

Depends. If you're using MFC and catching one of their exceptions, by all means, do it their way. Same goes for any framework: when in Rome, do as the Romans. Don't try to force a framework into your way of thinking, even if "your" way of thinking is "better." If you decide to use a framework, embrace its way of thinking — use the idioms that its authors expected you to use.

如果在使用MFC時(shí),使用自帶的exception,不要用自己的exception。

But if you're creating your own framework and/or a piece of the system that does not directly depend on MFC, then don't catch by pointer just because MFC does it that way. When you're not in Rome, you don't necessarily do as the Romans. In this case, you should not. Libraries like MFC predated the standardization of exception handling in the C++ language, and some of these libraries use a backwards-compatible form of exception handling that requires (or at least encourages) you to catch by pointer.

當(dāng)自己寫架構(gòu)時(shí),系統(tǒng)的一部分不依賴于MFC,不要像MFC那樣按指針傳遞。

像MFC等庫出現(xiàn)早于C++標(biāo)準(zhǔn)異常處理,一些庫都采用向下兼容的異常處理方式,需要(至少鼓勵(lì))你按指針傳遞。

按指針傳遞會(huì)有上述表格中的問題。



總結(jié)

以上是生活随笔為你收集整理的C++ exception的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。