Skip to main content

IAR Embedded Workbench for RISC-V 3.40

COP-dtor (C++ only)

In this section:
Synopsis

A class which dynamically allocates memory in its copy control functions does not have a destructor.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.png
Full description

A class which dynamically allocates memory in its copy control functions does not have a destructor. This will most likely result in a memory leak. If memory is dynamically allocated in the constructors or assignment operators, there must be a matching destructor to free it. If a destructor is not defined, the compiler will synthesize one, which will destroy any pointers but will not release their contents back to the heap. Even if this is intentional (and the memory is released elsewhere) it is still dangerous, because it subverts the Resource Acquisition is Initialization convention, and consequently users of the class might not release the memory at all. This check should only be used if all of a class' copy control functions are defined in the same file.

Coding standards
CWE 401

Improper Release of Memory Before Removing Last Reference ('Memory Leak')

Code examples

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

class MyClass{
  int* p;

public:
  MyClass(){
    p = new int;
  }
};

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

class MyClass{
  int* p;

 public:
  MyClass(){
    p = new int;
  }

  ~MyClass(){
    delete p;
  }
};