The new operator allocates storage and constructs an object of the requested type. The central maintenance rule is to pair its form with the matching delete form. section 6.3 section 10.7
Mistake: using the wrong allocation or release form
A single double requires `new double`, not `new int`. An array allocated with `new double[count]` requires `delete [] scores`, not `delete scores`; mismatching the forms causes undefined behavior. A constructed object also needs its destructor to run, as `delete buf` does for `new Buffer(25)`. section 6.3 section 10.7
Apply these pairings when maintaining dynamic allocation:
- Use `new T` with `delete pointer` for one object. section 10.7
- Use `new T[count]` with `delete [] pointer` for an array. section 10.7
- Prefer `std::vector` in most cases where a resizable collection is needed, while recognizing that arrays remain in existing code. section 10.7
Listing 10.14 Properly pairing new and delete operators
int main() {
int count;
std::cout << "Enter number of items to average: ";
std::cin >> count;
double* scores = new double[count]; #1
for (int i = 0; i < count; ++i) {
std::cout << "Enter score: ";
std::cin >> scores[i];
}
double sum = 0.0;
for (int i = 0; i < count; ++i)
sum += scores[i];
delete [] scores; #2
if (count > 0)
std::cout << "Average score is " << sum/count << '\n';
else
std::cout << "No items to average\n";
return 0;
}
Compare the corrected runtime-sized score array with the mismatched deletion in the problematic version. section 10.7
