CWARN.COPY.NOASSIGN

Class defines copy constructor, but no assignment operator

The CWARN.COPY.NOASSIGN checker finds classes that define a copy constructor, but no assignment operator.

Vulnerability and risk

The default copy constructor and assignment operator generated by the C++ compiler perform a bit-wise copy of class data members. If members are overwritten, memory might not be disposed of properly. This situation can lead to leaked memory and unreleased resources.

Mitigation and prevention

To address the problem, always provide an explicit implementation of the assignment operator for classes that contain dynamically allocated data members, and always ensure that there is a deep copy of those data members.

Vulnerable and fixed code example

Copy
  class A      
  {
  public:
      A(const A &other);
  };
  
  class B
  {
  public:
     B(const B &other);
     B &operator=(const B &other);
 };
 
 class C
 {
 public:
     void f() {}
 };

In this code example, Klocwork flags class A, since it defines a copy constructor and no assignment operator. In contrast, class B defines both a copy constructor and an assignment operator, and doesn't get flagged.