C++核心準(zhǔn)則E.12: 當(dāng)不可能或不愿意通過(guò)拋出異常退出函數(shù)時(shí)使用noexcept

E.12: Use?noexcept?when exiting a function because of a?throw?is impossible or unacceptable
E.12: 當(dāng)不可能或不愿意通過(guò)拋出異常退出函數(shù)時(shí)使用noexcept
Reason(原因)
To make error handling systematic, robust, and efficient.
為了讓錯(cuò)誤處理更系統(tǒng)化,健壯和高效。
Example(示例)
double compute(double d) noexcept
{
return log(sqrt(d <= 0 ? 1 : d));
}
Here, we know that?compute?will not throw because it is composed out of operations that don't throw. By declaring?compute?to be?noexcept, we give the compiler and human readers information that can make it easier for them to understand and manipulate?compute.
因?yàn)檫@段代碼有不會(huì)拋出異常的操作構(gòu)成,所以我們知道compute函數(shù)不會(huì)拋出異常。通過(guò)將compute函數(shù)定義為noexcept,我向編譯器和代碼的讀者傳遞了可以讓它們更容易理解和維護(hù)代碼的信息。
Note(注意)
Many standard-library functions are?noexcept?including all the standard-library functions "inherited" from the C Standard Library.
很多標(biāo)準(zhǔn)庫(kù)函數(shù)被定義為noexcept,包含所有從C標(biāo)準(zhǔn)庫(kù)繼承的標(biāo)準(zhǔn)庫(kù)函數(shù)。
Example(示例)
vector munge(const vector& v) noexcept
{
vector v2(v.size());
// ... do something ...
}
The?noexcept?here states that I am not willing or able to handle the situation where I cannot construct the local?vector. That is, I consider memory exhaustion a serious design error (on par with hardware failures) so that I'm willing to crash the program if it happens.
這里的noexcept說(shuō)明我不愿意或者不能處理局部的vecrot構(gòu)建失敗的情況。也就是說(shuō),我認(rèn)為內(nèi)存耗盡是嚴(yán)重的設(shè)計(jì)錯(cuò)誤(和硬件錯(cuò)誤同樣看待),如果這種情況發(fā)生,我甘愿終止程序。
Note(注意)
Do not use traditional?exception-specifications.
不要使用傳統(tǒng)的例外定義方式。
See also(參見(jiàn))
discussion.
課題討論。
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e12-use-noexcept-when-exiting-a-function-because-of-a-throw-is-impossible-or-unacceptable
新書(shū)介紹
以下是本人3月份出版的新書(shū),拜托多多關(guān)注!

本書(shū)利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過(guò)可執(zhí)行的示例對(duì)23 個(gè)設(shè)計(jì)模式逐個(gè)進(jìn)行說(shuō)明。這樣一方面可以使讀者了解真實(shí)的軟件開(kāi)發(fā)工作中每個(gè)設(shè)計(jì)模式的運(yùn)用場(chǎng)景和想要解決的問(wèn)題;另一方面通過(guò)對(duì)這些問(wèn)題的解決過(guò)程進(jìn)行說(shuō)明,讓讀者明白在編寫(xiě)代碼時(shí)如何判斷使用設(shè)計(jì)模式的利弊,并合理運(yùn)用設(shè)計(jì)模式。
對(duì)設(shè)計(jì)模式感興趣而且希望隨學(xué)隨用的讀者通過(guò)本書(shū)可以快速跨越從理解到運(yùn)用的門(mén)檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書(shū)中的示例作為設(shè)計(jì)和開(kāi)發(fā)的參考;使用Python 語(yǔ)言進(jìn)行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書(shū)中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
