delete releases storage obtained for one object with new and destroys that object. Pairing the wrong allocation and deallocation forms produces undefined behavior and can leave the program in an unknown state. section 6.3 section 10.7
Match the form of delete to the form of new:
- Use delete for a single object allocated with new, such as new Buffer(25). section 6.3
- Use delete[] for an array allocated with new[], such as new double[count]. section 10.7
- Do not use delete or delete[] for memory obtained with malloc; pair malloc with free, and do not mix these families. section 6.3
Listing 6.6 Using new and free in a disciplined manner
struct Buffer {
char* str;
Buffer(int size) : str(new char[size+1]) { str[0] = '\0'; }
~Buffer() { delete[] str; }
};
int main() {
// double* val = new int; #1
double* val = new double; #2
std::cout << val << '\n';
Buffer* buf = new Buffer(25); #3
std::cout << buf->str << ", size " << strlen(buf->str) << '\n';
delete buf; #4
return 0;
}
Compare disciplined new/delete usage: the Buffer destructor uses delete[] for its character array, while the Buffer object itself uses delete. section 6.3
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;
}
The corrected averaging example replaces delete scores with delete[] scores after allocating the runtime-sized array with new[]. section 10.7
