I got really stuck trying to deallocate memory using delete without it being in a for loop.
MyClass *Array[10];
cout << "Step 1 - Allocation" << endl << endl;
Array[0] = new MyClass();
Array[1] = new MyClass();
Array[2] = new MyClass(2, 4.6);
Array[3] = new MyClass(*Array[2]);
Array[4] = new MyClass();
Array[5] = new MyClass(13, 66.6);
Array[6] = new MyClass(75, 9.43);
Array[7] = new MyClass(*Array[6]);
Array[8] = new MyClass(*Array[1]);
Array[9] = new MyClass(*Array[3]);
cout << endl << "Step 2 - Write" << endl << endl;
for(int i=0; i<10; i++)
{
Array[i]->write();
cout << endl;
}
cout << endl << "Step 3 - Deallocation" << endl << endl;
I tried delete[] Array, but it doesn’t work.
The code must stay as it is as it’s correct by what is asked to do. The only thing is to add a delete (single-lined and not a for loop) to delete Array.
You need to delete each object that you’ve created using
new:Arrayitself is a local variable; you did not usenewto create it, so you do not usedeleteto destroy it. It will be destroyed when it goes out of scope.To address the updated constraint that the deletion must be done “single-lined and not a for loop,” one could, I suppose, write:
This is a single line of code and uses no loops. It is not possible to use a single
deleteexpression to destroy what are ten effectively unrelated objects.But do not do this. Really. Manual resource management is dangerous and very difficult to do correctly. C++ has automatic resource management capabilities and you should use them. In this case, it would be far better to use a
std::vector<MyClass>:There’s no
newin this example, thus nodeleteis required. Thestd::vectorwill clean everything up when it is destroyed.