問題描述
throw()
和 noexcept
除了分別在運行時和編譯時檢查之外,還有什么區別嗎?
Is there any difference between throw()
and noexcept
other than being checked at runtime and compile time, respectively?
這篇維基百科 C++11 文章表明 C++03 拋出說明符已棄用.
為什么是這樣,noexcept
是否足以在編譯時涵蓋所有這些內容?
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 ?
[注意:我檢查了這個問題和這篇文章,但無法確定棄用的確切原因.]
[Note: I checked this question and this article, but couldn't determine the solid reason for deprecation.]
推薦答案
異常說明符已被棄用,因為異常說明符通常是一個糟糕的主意.添加 noexcept
是因為它是異常說明符的一個相當有用的用法:知道函數何時不會拋出異常.因此它變成了一個二元選擇:會拋出的函數和不會拋出的函數.
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 說明符,因為 noexcept
更強大.noexcept
可以有一個編譯時解析為布爾值的參數.如果布爾值為真,則 noexcept
堅持.如果布爾值為 false,則 noexcept
不會粘住,函數可能會拋出.
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.
因此,您可以執行以下操作:
Thus, you can do something like this:
struct<typename T>
{
void CreateOtherClass() { T t{}; }
};
CreateOtherClass
會拋出異常嗎?它可能,如果 T
的默認構造函數可以.我們怎么講?像這樣:
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{}; }
};
因此,如果給定類型的默認構造函數拋出,CreateOtherClass()
將拋出.這解決了異常說明符的主要問題之一:它們無法向上傳播調用堆棧.
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()
做到這一點.
You can't do this with throw()
.
這篇關于C++03 throw() 說明符 C++11 noexcept 之間的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!