Dela via


Varning C26440

Funktionen kan deklareras som "noexcept".

C++ Core Guidelines F.6: Om funktionen inte får utlösas deklarerar du den noexcept

Om koden inte ska orsaka några undantag bör den markeras med hjälp noexcept av specificeraren. Den här kommentaren hjälper till att förenkla felhanteringen på klientkodsidan och gör det möjligt för kompilatorn att göra fler optimeringar.

Anmärkningar

  • En funktion betraktas som icke-utlösande om:
    • Den har inga uttryckliga throw instruktioner.
    • funktionsanrop i dess kropp, om några, anropar endast funktioner som sannolikt inte kommer att utlösas: constexpr eller funktioner som är markerade med någon undantagsspecifikation som medför icke-kastande beteende (inklusive vissa icke-standardspecifikationer).
  • Icke-standard- och inaktuella specificerare som throw() eller __declspec(nothrow) är inte likvärdiga med noexcept.
  • Explicita specificerare noexcept(false) och noexcept(true) respekteras på lämpligt sätt.
  • Funktioner som har markerats som constexpr ska inte orsaka undantag och analyseras inte.
  • Regeln gäller även lambda-uttryck.
  • Logiken betraktar inte rekursiva anrop som potentiellt icke-kast. Den här logiken kan ändras i framtiden.

Exempel

Alla funktioner utom destruktor varnar eftersom de saknar 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'
};

Med noexcept som dekorerar samma struktur tas alla varningar bort.

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*/}
};