Swap may throw
Description
This defect occurs if a swap function is not explicitly specified as
noexcept or noexcept(true) in C++11 or later. For
C++03 and earlier, this defect occurs if the swap function is not explicitly specified as
throw(). Polyspace® checks free swap functions, member swap functions, and friend swap
function.
Risk
Use of swap functions that may raise exception introduces these risks and disadvantages:
The compiler is required to generate exception handling code for each caller function of
swap. The caller functions become less efficient if the swap function is not explicitly specified to not throw exceptions..The use of the copy-and-swap idiom is prevented, resulting in copy and move assignment operators that lack strong exception guarantees.
Parts of the Standard Template Library (STL) executes more expensive code to avoid throwing exceptions. If the exception specification of a
swapfunction permits exceptions, the code incurs avoidable performance overhead and execute less efficiently than intended.
Fix
To fix this defect, specify the swap function as noexcept or
noexcept(true) in C++11 or later. For C++03 and earlier, specify the
swap function as throw().
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
| Group: Performance |
| Language: C++ |
| Default: Off |
Command-Line Syntax:
SWAP_MAY_THROW
|
| Impact: Medium |
PQL Name:
std.defects.SWAP_MAY_THROW
|
Version History
Introduced in R2026a
See Also
Find defects
(-checkers) | Destructor may
throw | C++ standard version
(-cpp-version) | A move operation may
throw | AUTOSAR C++14 Rule
A15-5-1
Topics
- Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Polyspace Results Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)
- Expensive-to-Read Objects in Bug Finder