CRITICAL
Rule Definition
A copy constructor is highly recommended to avoid surprises when an object is initialized using an object of the same type. If an object manages the allocation and deallocation of an object on the heap (the managing object has a pointer to the object to be created by the class' constructor), only the value of the pointer will be copied. This can lead to two invocations of the destructor for the same object (on the heap), probably resulting in a run-time error.
Remediation
Define a copy constructor for the class.
Violation Code Sample
#include <string.h>
class String
{
public:
String( const char* cp = ""); // Constructor
~String(); // Destructor
// ...
private:
char* sp;
// ...
};
String::String(const char* cp) // Constructor
{
sp = new char[strlen(cp)];
strcpy(sp,cp);
}
String::~String() // Destructor
{
delete sp;
}
// "Dangerous" String class
void
main()
{
String w1;
String w2 = w1;
// WARNING: IN A BITWISE COPY OF w1::sp,
// THE DESTRUCTOR FOR W1::SP WILL BE CALLED TWICE:
// FIRST, WHEN w1 IS DESTROYED; AGAIN, WHEN w2 IS DESTROYED.
}
Fixed Code Sample
#include <string.h>
class String
{
public:
String( const char* cp = ""); // Constructor
String( const String& sp ); // Copy constructor
~String(); // Destructor
// ...
private:
char* sp;
// ...
};
String::String( const char* cp ) // Constructor
{
sp = new char[strlen(cp)];
strcpy(sp,cp);
}
String::String( const String& stringA ) : sp( new char[strlen(stringA.sp)] )
{
strcpy(sp,stringA.sp);
}
String::~String() // Destructor
{
delete sp;
}
// "Safe" String class
void
main()
{
String w1;
String w2 = w1; // SAFE COPY: String::String( const String& ) CALLED.
}
Related Technologies
C++
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.