Consider the following two ways to get space for an array of 10 string objects, one using malloc, the other using new:
string *stringArray1 = static_cast(malloc(10 * sizeof(string))); string *stringArray2 = new string[10];
Here stringArray1 points to enough memory for 10 string objects, but no objects have been constructed in that memory. Furthermore, you have no way to initialize the objects in the array.
In contrast, stringArray2 points to an array of 10 fully constructed string objects, each of which can safely be used in any operation taking a string. The call to free will release the memory pointed to by stringArray1, but no destructors will be called on the string objects in that memory.
If the string objects themselves allocated memory, as string objects are wont to do, all the memory they allocated will be lost. On the other hand, when delete is called on stringArray2, a destructor is called for each object in the array before any memory is released.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|