Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3654

Destructors should be "noexcept"

    XMLWordPrintable

    Details

    • Message:
      Ensure that this destructor is exception-free and declare it "noexcept".
    • Highlighting:
      Hide

      destructor name

      Show
      destructor name
    • Default Severity:
      Blocker
    • Impact:
      High
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C, C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Scope:
      Main Sources, Test Sources
    • CppCoreGuidelines:
      C.36,C.37

      Description

      Throwing an exception from a destructor results in undefined behavior, meaning that your program could be terminated abruptly without neatly destroying others objects.

      Thus destructors should never throw exceptions. Instead, they should catch and handle those thrown by the functions they call, and be noexcept.

      This rule raises an issue when a destructor is not noexcept. By default, destructors are noexcept, therefore most of the time, nothing needs to be written in the source code. A destructor is not noexcept if:

      • the base class or a data member has a non noexcept destructor,
      • the destructor is decorated with the noexcept keyword followed by something that evaluates to false.

      Noncompliant Code Example

      struct A {
        ~A() noexcept(false) {} // Noncompliant
      };
      
      struct C {
        /* ... */
        A a; // This member data prevents automatic declaration of the destructor as noexcept
        ~C() { // Noncompliant
          /* ... */
        }
      };
      

      Compliant Solution

      struct A {
        ~A() noexcept(true) {}
      };
      
      struct C {
        /* ... */
        A a;
        ~C() { // Compliant, noexcept by default
          /* ... */
        }
      };
      

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              alban.auzeill Alban Auzeill
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: