共用方式為


警告 C26440

函式可以宣告為 'noexcept'。

C++ 核心指導方針 F.6 :如果您的函式可能未擲回,請宣告它 noexcept

如果程式碼不應該造成任何例外狀況,則應該使用 noexcept 規範來標記它。 此批註有助於簡化用戶端程式代碼上的錯誤處理,並讓編譯器執行更多優化。

備註

  • 如果下列狀況,則會將函式視為非擲回:
    • 它沒有明確的 throw 語句;
    • 函式會在其主體中呼叫,如果有的話,只會叫用不太可能擲回的函式: constexpr 或以任何例外狀況規格標示的函式,而需要非擲回行為(包括某些非標準規格)。
  • 非標準和過期規範,例如 throw()__declspec(nothrow) 不等於 noexcept
  • 明確規範 noexcept(false)noexcept(true) 會適當地受到尊重。
  • 標示為 constexpr 的函式不應該造成例外狀況,也不會進行分析。
  • 此規則也適用于 Lambda 運算式。
  • 邏輯不會將遞迴呼叫視為可能不擲回。 此邏輯未來可能會變更。

範例

解構函式以外的所有函式都會發出警告,因為它們遺漏 noexcept。

struct S
{
    S() {} // C26455, Default constructor may not throw. Declare it 'noexcept'
    ~S() {}

    S(S&& s) {/*impl*/} // C26439, This kind of function may not throw. Declare it 'noexcept' (f.6)
    S& operator=(S&& s) {/*impl*/} // C26439, This kind of function may not throw. Declare it 'noexcept' (f.6)

    S(const S& s) {/*impl*/} // C26440, This function can be declared 'noexcept'
    S& operator=(const S& s) {/*impl*/} // C26440, This function can be declared 'noexcept'
};

由於 noexcept 裝飾相同的結構,會移除所有警告。

struct S
{
    S() noexcept {}
    ~S() {}

    S(S&& s) noexcept {/*impl*/}
    S& operator=(S&& s) noexcept {/*impl*/}

    S(const S& s) noexcept {/*impl*/}
    S& operator=(const S& s) noexcept {/*impl*/}
};