I'm reading C++ Primer Plus, 12.1.3, about memory, and some things about destructor really confuse me.
//Here is a default construtor of String class
String::String()
{
len = 0;
str = new char[1];
str[0] = '\0';
}
and the book says, use str = new char[1]
not str = new char
, the two ways allocate same memory, but the 2nd is not compatible with destructor. Besides, the book says the below 3 ways is bad because they are not compatible with "delete"
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
I don't know what are the difference that make these 3 ways bad, can someone explain it to me? Thank you very much.