問(wèn)題描述
我發(fā)現(xiàn)有3種方法可以捕獲異常,有什么區(qū)別?
I found that there are three ways to catch an exception, what are the differences?
1) 按值捕獲;
2) 按引用捕獲;
3) 通過(guò)指針捕捉;
我只知道按值捕獲會(huì)調(diào)用對(duì)象的兩個(gè)副本,按引用捕獲會(huì)調(diào)用一個(gè).那么如何通過(guò)指針捕獲呢?什么時(shí)候用指針捕捉?除了拋出一個(gè)對(duì)象,我還能像這樣拋出一個(gè)指向?qū)ο蟮闹羔槅?
I only know that catch by value will invoke two copies of the object, catch by reference will invoke one. So how about catch by pointer? When to use catch by pointer? In addition to throw an object, can I throw a pointer to an object like this?
class A {}
void f() {
A *p = new A();
throw p;
}
推薦答案
推薦的方式是按值拋出,按引用捕獲.
您的示例代碼拋出一個(gè)指針,這是一個(gè)壞主意,因?yàn)槟仨氃诓东@站點(diǎn)管理內(nèi)存.
Your example code throws a pointer, which is a bad idea since you would have to manage memory at the catch site.
如果你真的覺(jué)得你應(yīng)該拋出一個(gè)指針,使用智能指針,比如 shared_ptr
.
If you really feel you should throw a pointer, use a smart pointer such as shared_ptr
.
無(wú)論如何,Herb Sutter 和 Alexei Alexandrescu 在我轉(zhuǎn)述的他們的 C++ 編碼標(biāo)準(zhǔn)一書(shū)中很好地解釋了這一點(diǎn).
請(qǐng)參閱 C++ 編碼標(biāo)準(zhǔn):按值拋出,按引用捕獲.
這篇關(guān)于C++中通過(guò)指針捕獲異常的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!