AutosarC++18_03-A12.8.5¶
A copy assignment and a move assignment operator shall handle self-assignment
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
User-defined copy assignment operator and move assignment operator need to prevent self-assignment, so the operation will not leave the object in an indeterminate state. If the given parameter is the same object as the local object, destroying object-local resources will invalidate them. It violates the copy/move assignment postconditions.
Note that STL containers assume that self-assignment of an object is correctly handled.
Otherwise it may lead to unexpected behavior of an STL container.
Self-assignment problem can also be solved using swap operators. See rule: A12-8-2.
Example
// $Id: A12-8-5.cpp 271773 2017-03-23 13:16:53Z piotr.tanski $
#include <cstdint>
#include <stdexcept>
struct A {
std::int32_t number;
std::int32_t *ptr;
// Implementation
};
class B {
public:
// ...
B &operator=(B const &oth) // Non-compliant
{
i = oth.i;
delete aPtr;
try {
aPtr = new A(*oth.aPtr); // If this is the self-copy case, then
// the oth.a_ptr is already deleted
} catch (std::bad_alloc &) {
aPtr = nullptr;
}
return *this;
}
private:
std::int16_t i = 0;
A *aPtr = nullptr;
};
class C {
public:
C &operator=(C const &oth) // Compliant
{
if (this != &oth) {
A *tmpPtr = new A(*oth.aPtr);
i = oth.i;
delete aPtr;
aPtr = tmpPtr;
}
return *this;
}
C &operator=(C &&oth) // Compliant
{
if (this != &oth) {
A *tmpPtr = new A{std::move(*oth.aPtr)};
i = oth.i;
delete aPtr;
aPtr = tmpPtr;
}
return *this;
}
private:
std::int16_t i = 0;
A *aPtr = nullptr;
};
See Also
- SEI CERT C++ [9]: OOP54-CPP Gracefully handle self-assignment.
- C++ Core Guidelines [10]: C.62: Make copy assignment safe for self-assignment.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
incomplete_swap |
Swap does not handle all non-static data members. |
None |
False |
self_assignment |
Missing or non-compliant guard against self-assignment. |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allowed_comparison_operators¶
allowed_comparison_operators : set[bauhaus.ir.PIR_Class_Name] = {'Equal', 'Unequal'}
self_assignment_check_must_be_first_statement¶
self_assignment_check_must_be_first_statement : bool = False