The Revised Default Constructor

The new default constructor merits notice. It look likes this:

String::String()
{
    len = 0;
    str = new char[1];
    str[0] = '';               // default string
}

You might wonder why the code uses

str = new char[1];

and not this:

str = new char;

Both forms allocate the same amount of memory. The difference is that the first form is compatible with the class destructor and the second is not. Recall that the destructor contains this code:

delete [] str;

Using delete [] is compatible with pointers initialized by using new [] and with the null pointer. So another possibility would be to replace

str = new char[1];
str[0] = '';               // default string

with this:

str = 0; // sets str to the null pointer

The effect of using delete [] with any pointers initialized any other way is undefined:

char words[15] = "bad idea";
char * p1= words;
char * p2 = new char;
char * p3;
delete [] p1; // undefined, so don't do it
delete [] p2; // undefined, so don't do it
delete [] p3; // undefined, so don't do it

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.172.93