Skip to main content

IAR Embedded Workbench for RX 5.20

COP-assign-op-self (C++ only)

In this section:
Synopsis

Assignment operator does not check for self-assignment before allocating member functions

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

An assignment operator does not check for self-assignment before allocating member functions. If self-assignment occurs in a user-defined object which uses dynamic memory allocation, references to allocated memory will be lost if they are reassigned. This will most likely cause a memory leak, as well as unexpected results, because the objects referred to by any pointers are lost.

Coding standards
CERT MEM42-CPP

Ensure that copy assignment operators do not damage an object that is copied to itself

Code examples

The following code example fails the check and will give a warning:

class MyClass{
  int* p;
  MyClass& operator=(const MyClass& rhs){
    p = new int(*(rhs.p));  //reference to the old 
                            //memory is lost
    return *this;
  }
};

The following code example passes the check and will not give a warning about this issue:

class MyClass{
  int* p;
  MyClass& operator=(const MyClass& rhs){
    if (&rhs != this)  //the pointer is not reallocated
                       //if the object is assigned to itself
      p = new int(*(rhs.p));
    return *this;
  }
};