問題描述
throw()
和 noexcept
除了分別在運(yùn)行時(shí)和編譯時(shí)檢查之外,還有什么區(qū)別嗎?
Is there any difference between throw()
and noexcept
other than being checked at runtime and compile time, respectively?
這篇維基百科 C++11 文章表明 C++03 拋出說明符已棄用.
為什么是這樣,noexcept
是否足以在編譯時(shí)涵蓋所有這些內(nèi)容?
This Wikipedia C++11 article suggests that the C++03 throw specifiers are deprecated.
Why so, is noexcept
capable enough to cover all that at compile time ?
[注意:我檢查了這個(gè)問題和這篇文章,但無法確定棄用的確切原因.]
[Note: I checked this question and this article, but couldn't determine the solid reason for deprecation.]
推薦答案
異常說明符已被棄用,因?yàn)楫惓Uf明符通常是一個(gè)糟糕的主意.添加 noexcept
是因?yàn)樗钱惓Uf明符的一個(gè)相當(dāng)有用的用法:知道函數(shù)何時(shí)不會(huì)拋出異常.因此它變成了一個(gè)二元選擇:會(huì)拋出的函數(shù)和不會(huì)拋出的函數(shù).
Exception specifiers were deprecated because exception specifiers are generally a terrible idea. noexcept
was added because it's the one reasonably useful use of an exception specifier: knowing when a function won't throw an exception. Thus it becomes a binary choice: functions that will throw and functions that won't throw.
noexcept
而不是刪除除 throw()
之外的所有 throw 說明符,因?yàn)?noexcept
更強(qiáng)大.noexcept
可以有一個(gè)編譯時(shí)解析為布爾值的參數(shù).如果布爾值為真,則 noexcept
堅(jiān)持.如果布爾值為 false,則 noexcept
不會(huì)粘住,函數(shù)可能會(huì)拋出.
noexcept
was added rather than just removing all throw specifiers other than throw()
because noexcept
is more powerful. noexcept
can have a parameter which compile-time resolves into a boolean. If the boolean is true, then the noexcept
sticks. If the boolean is false, then the noexcept
doesn't stick and the function may throw.
因此,您可以執(zhí)行以下操作:
Thus, you can do something like this:
struct<typename T>
{
void CreateOtherClass() { T t{}; }
};
CreateOtherClass
會(huì)拋出異常嗎?它可能,如果 T
的默認(rèn)構(gòu)造函數(shù)可以.我們?cè)趺粗v?像這樣:
Does CreateOtherClass
throw exceptions? It might, if T
's default constructor can. How do we tell? Like this:
struct<typename T>
{
void CreateOtherClass() noexcept(is_nothrow_default_constructible<T>::value) { T t{}; }
};
因此,如果給定類型的默認(rèn)構(gòu)造函數(shù)拋出,CreateOtherClass()
將拋出.這解決了異常說明符的主要問題之一:它們無法向上傳播調(diào)用堆棧.
Thus, CreateOtherClass()
will throw iff the given type's default constructor throws. This fixes one of the major problems with exception specifiers: their inability to propagate up the call stack.
你不能用 throw()
做到這一點(diǎn).
You can't do this with throw()
.
這篇關(guān)于C++03 throw() 說明符 C++11 noexcept 之間的區(qū)別的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!