C++ exception
今天看書發(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试题整理 2:求链表倒数第 k 个结点
- 下一篇: 《深度探索C++对象模型》--7 站在对