CRITICAL
Rule Definition
If you do not define a copy constructor for a class that has pointer members, there is a risk of memory corruption that can lead to crashes or erroneous data.
A copy constructor is a special constructor that can be called to copy an object. The copy constructor for class X has the form X::X(const X&). In the code fragment below, s2 is created by calling String's copy constructor to copy s1:
String s1("Hello, world!");
String s2 (s1);
The copy constructor is called more often behind the scenes whenever the compiler needs a copy of an object. These objects, appropriately called temporaries, are created and destroyed as they are needed by the compiler. The most common place this occurs is during function calls, so that the semantics of call-by-value can be preserved. For example, here is a function that takes a String argument:
void DisplayError (const String s);
Whenever DisplayError() is called, the compiler generates a call to the copy constructor for String to create a temporary for parameters. The temporary is then passed to the function.
If you do not provide a copy constructor, the compiler will generate one for you automatically. This generated copy constructor simply performs a member-wise assignment of all of the data members of a class. This is fine for a class that does not contain any pointer variables, but for pointers this would lead to duplicate references to the same objects with the risk of invalid references and thus of memory corruption and crashes. It is a good idea to get into the habit of always providing the copy constructor for your classes.
Remediation
Define a copy constructor to properly manage pointer data members.
Violation Code Sample
class MyClass {
char * apointermember;
};
Fixed Code Sample
class MyClass {
MyClass( const MyClass&);
char * apointermember;
};
MyClass::MyClass( const MyClass& a)
{
/* Must be adapted to your case */
strcpy( apointermember, a.apointermember);
}
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.