1 .. title:: clang-tidy - bugprone-unhandled-self-assignment
3 bugprone-unhandled-self-assignment
4 ==================================
6 `cert-oop54-cpp` redirects here as an alias for this check. For the CERT alias,
7 the `WarnOnlyIfThisHasSuspiciousField` option is set to `false`.
9 Finds user-defined copy assignment operators which do not protect the code
10 against self-assignment either by checking self-assignment explicitly or
11 using the copy-and-swap or the copy-and-move method.
13 By default, this check searches only those classes which have any pointer or C array field
14 to avoid false positives. In case of a pointer or a C array, it's likely that self-copy
15 assignment breaks the object if the copy assignment operator was not written with care.
18 `OOP54-CPP. Gracefully handle self-copy assignment
19 <https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP54-CPP.+Gracefully+handle+self-copy+assignment>`_
21 A copy assignment operator must prevent that self-copy assignment ruins the
22 object state. A typical use case is when the class has a pointer field
23 and the copy assignment operator first releases the pointed object and
24 then tries to assign it:
32 T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
37 T& operator=(const T &rhs) {
44 There are two common C++ patterns to avoid this problem. The first is
45 the self-assignment check:
53 T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
58 T& operator=(const T &rhs) {
68 The second one is the copy-and-swap method when we create a temporary copy
69 (using the copy constructor) and then swap this temporary object with ``this``:
77 T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
87 T& operator=(const T &rhs) {
93 There is a third pattern which is less common. Let's call it the copy-and-move method
94 when we create a temporary copy (using the copy constructor) and then move this
95 temporary object into ``this`` (needs a move assignment operator):
103 T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
108 T& operator=(const T &rhs) {
110 *this = std::move(t);
114 T& operator=(T &&rhs) {
121 .. option:: WarnOnlyIfThisHasSuspiciousField
123 When `true`, the check will warn only if the container class of the copy
124 assignment operator has any suspicious fields (pointer, C array and C++ smart
126 This option is set to `true` by default.