Wednesday, May 30, 2007

Necessity of copy constructors

Exception to Rule 25
Sometimes, it is desired to let objects in a class share a data area. In such a case, it is not necessary to define a copy constructor. Instead, it is necessary to make sure that this data area is not deallocated as long as there are pointers to it.
Exception to Rule 26
No exceptions.
Example 25: Definition of a "dangerous" class not having a copy constructor
#include

class String
{
public:
String(
const char* cp = ""); // Constructor
~String(); // Destructor
// ...
private:
char*
sp;
// ...
};

String::String(const char* cp) : sp( new char[strlen(cp)] ) // Constructor
{
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.
}

Example 26: "Safe" class having copy constructor and default constructor
#include

class String
{
public:
String( const char* cp = ""); // Constructor
String( const String& sp ); // Copy constructor
~String(); // Destructor
// ...
private:
char* sp;
// ...
};

String::String( const char* cp ) : sp( new char[strlen(cp)] ) // Constructor
{
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.
}

No comments: