Using malloc for a C++ object can skip its constructor; using the wrong allocation size can also cause out-of-bounds access. The new operator allocates storage and constructs an object, so its type and matching deallocation matter. section 6.3
Match the allocation form to the object and its cleanup:
- Use new Type for one object and delete for that object; class construction and destruction handle its lifetime. section 6.3
- Use new Type[count] for an array and delete[] to release it. Pairing array allocation with plain delete causes undefined behavior. section 10.7
- Prefer std::vector in most cases when managing a collection; where legacy code constrains changes, correct mismatched forms incrementally and test. section 10.7
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 scalar allocation and object construction with the matching cleanup, including a Buffer whose destructor releases its character array. 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;
}
See an array allocated with new[] and correctly released with delete[]. section 10.7
