Skip to main content

IAR Embedded Workbench for RL78 5.20

COP-copy-ctor (C++ only)

In this section:
Synopsis

A class which uses dynamic memory allocation does not have a user-defined copy constructor.

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

A class which uses dynamic memory allocation does not have a user-defined copy constructor, so the compiler's synthesized copy constructor 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 copy constructor might be adequate and appropriate for classes whose members include only (non-pointer) built-in types, in a class that dynamically allocates memory, it might 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(){      //not a copy constructor
    p = new int;  //one will be synthesized
  }

  ~MyClass(){
    delete p;
  }
};

int main(){
  MyClass *original = new MyClass;
  MyClass 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;
 public:
 
  MyClass(MyClass& rhs){
    p = new int;
    *p = *(rhs.p);
  }
  
  ~MyClass(){
    delete p;
  }
};