Main Content

Destructor may throw

The signature of destructor permits raising exceptions

Since R2026a

Description

This defect occurs if either of these conditions are true:

  • A destructor signature explicitly permits raising exceptions using the noexcept(false) specification (C++11 and later) or a nonempty throw specification (C++03 and earlier).

  • A destructor signature implicitly permits raising exceptions. If the destructor is implicit or lacks an explicit exception specification, raising exceptions is permitted for C++03 and earlier. For C++11 and later, implicit destructors and destructors lacking an explicit exception specification are assumed to be noexcept(true).

Risk

Using destructors that can raise exceptions has these risks:

  • When an exception occurs, the compiler unwinds the stack and deletes objects by calling their destructors. If a destructor raises an exception during stack unwinding, the program terminates abnormally.

  • Destructors that are permitted to raise exceptions require the compiler to generate exception handling code in the code of the function that calls the destructor. Such code is less efficient than code that calls noexcept specified destructors.

  • Parts of the Standard Template Library (STL) executes more expensive code to avoid throwing exceptions. If the exception specification of a destructor permits exceptions, the code incurs avoidable performance overhead and execute less efficiently than intended.

Fix

To fix this defect:

  • Explicitly specify the destructor as noexcept, noexcept(true) or throw().

  • For C++11 or later, use the default destructor or the implicit destructor.

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

In this C++03 example, because the exception specification of the destructor is implicit, the destructor is permitted to raise exceptions. Specify the C++ version using the option -cpp-version. Polyspace® reports a defect.


        #include <string>

class Employee {
public:
	~Employee(); //Defect
	//...
private:
	std::string m_name;
};

Correction

To fix this defect, specify the destructor as throw().

#include <string>

class Employee {
public:
	~Employee() throw(); //No defect
	//...
private:
	std::string m_name;
};

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: DESTRUCTOR_MAY_THROW
Impact: Medium
PQL Name: std.defects.DESTRUCTOR_MAY_THROW

Version History

Introduced in R2026a