MISRA C++:2023 Dir 15.8.1
User-provided copy assignment operators and move assignment operators shall handle self-assignment
Since R2024b
Description
Directive Definition
User-provided copy assignment operators and move assignment operators shall handle self-assignment.
Rationale
If a class needs to manage resources, best practice is to use a manager class such as
smart pointers or containers from the C++ standard library. If using a manager class is not
possible, then the user-provided copy assignment operator and move assignment operator of
this class must be able to handle self-assignments. Consider a class
myClass
that manages the raw pointer data
. This
class shows a naive implementation of the copy assignment operator for the
class:
// Naive Copy Assignment Operator
myClass &operator=(const myClass &other) {
delete data;
data = new int(*other.data);
return *this;
}
This directive extends the CopyAssignable and MoveAssignable requirements to classes utilizing user-provided copy and move assignment operators. Avoid naive implementations of copy or move assignment operator. Use established idioms, such as copy-and-swap, when appropriate.
Polyspace Implementation
Polyspace® reports a violation of this rule if user-provided copy and move assignment operators do not check for self-assignment. Polyspace does not report a violation if a copy assignment operator uses the copy-and-swap idiom or if a move assignment operator uses a move-and-swap idiom.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Special member functions |
Category: Required |
Version History
Introduced in R2024b