V1002. A class, containing pointers, constructor and destructor, is copied by the automatically generated operator= or copy constructor.


The analyzer has detected a possible error that has to do with a call of an automatically generated copy constructor or assignment operator. Here are the conditions when such a call of compiler-generated functions is considered unsafe:

  • The class has a non-default constructor.
  • The class has a non-default destructor.
  • Some of the class members are pointers.

The pointer is very likely to refer to a buffer of memory allocated in the constructor and then freed in the destructor. Such objects should never be copied using such functions as memcpy or automatically generated functions (copy constructor, assignment operator).

Consider the following example:

class SomeClass
{
  int m_x, m_y;
  int *m_storagePtr;

public:
  SomeClass(int x, int y) : m_x(x), m_y(y)
  {
    m_storagePtr = new int[100];
    ....
  }
  ....
  ~SomeClass()
  {
    delete[] m_storagePtr;
  }
};

void Func()
{
  SomeClass A(0, 0);
  SomeClass B(A);           // <=
  ....
}

When copying object 'A' to object 'B' in this example, the pointer 'm_storagePtr' is copied from the 'A' object to the 'B' object. This is not what the programmer expected because they actually intended to copy the data rather than the pointers alone. This is what the fixed code should look like:

class SomeClass
{
  int m_x, m_y;
  int *m_storagePtr;

public:
  SomeClass(int x, int y) : m_x(x), m_y(y)
  {
    m_storagePtr = new int[100];
    ....
  }
  
  SomeClass(const SomeClass &other) : m_x(other.m_x), m_y(other.m_y)
  {
    m_storagePtr = new int[100];
    memcpy(m_storagePtr, other.m_storagePtr, 100 * sizeof(int));
  }
  
  ....

  ~SomeClass()
  {
    delete[] m_storagePtr;
  }
};

Similarly, this diagnostic detects errors that have to do with using a default assignment operator.

True, the analyzer may make a mistake and issue a false warning for a correct class, but we still recommend that you examine every V1002 warning carefully. If there is no error, specify explicitly that you intend to use automatically generated functions and that they are safe. To do that, use the keyword 'default':

T(const T &x) = default;
SomeClass &operator=(const T &x) = default;

This will make it easier for programmers who will be maintaining the code to see that it is correct, and prevent PVS-Studio from issuing false warnings as well.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-665.

You can look at examples of errors detected by the V1002 diagnostic.


Bugs Found

Checked Projects
344
Collected Errors
12 970