Skip to main content

IAR Embedded Workbench for Arm 9.70.x

COP-assign-op (C++ only)

In this section:
Synopsis

There is no assignment operator defined for a class whose destructor deallocates memory.

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

There is no assignment operator defined for a class whose destructor deallocates memory, so the compiler's synthesized assignment operator will be created and used if needed. This will only perform shallow copies of any pointer values, meaning that multiple instances of a class might inadvertently contain pointers to the same memory. Although a synthesized assignment operator might be adequate and appropriate for classes whose members include only (non-pointer) built-in types, in a class that dynamically allocates memory it could easily lead to unexpected behavior or attempts to access freed memory. In that case, if a copy is made and one of the two is destroyed, any deallocated pointers in the other will become invalid. This check should only be selected if all of a class' copy control functions are defined in the same file.

Coding standards

This check does not correspond to any coding standard rules.

Code examples

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

class MyClass{
  int* p;
public:  
  ~MyClass(){
    delete p;  //this class has no assignment operator
  }
};

int main(){
  MyClass *original = new MyClass;
  MyClass copy;
  copy = *original;  //copy's p == original's p
  delete original;  //p is deallocated; copy now has an invalid pointer
}

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

class MyClass{
  int* p;
  
  ~MyClass(){
    delete p;  //OK - the assignment operator will
               //not be synthesized
  }
  
  MyClass& operator=(const MyClass& rhs){
    if (this != &rhs)
      p = new int;
    return *this;
  }
};