主要内容

Swap may throw

Signature of swap function permits raising exceptions

Since R2026a

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 swap function 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

expand all

In this example, the function swap() swaps objects of type Employee. Because this function is not specified as noexcept, Polyspace reports a defect.


#include <string>
class Employee {
public:
	std::string get_name() const;
	void set_name(const std::string &);
private:
	std::string m_name;
};

void swap(Employee &lhs, Employee &rhs); //Defect
Correction

To fix this defect, specify the swap() function as noexcept. For C++03 or earlier, specify the function as throw().


#include <string>
class Employee {
    public:
      std::string get_name() const;
      void set_name(const std::string&);
    private:
      std::string m_name;
    };

void swap(Employee& lhs, Employee& rhs) noexcept; //No defect

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