liveBook · Manning

New operator

As explained in 100 C++ Mistakes and How to Avoid Them

new is a C++ expression that allocates storage and constructs an object of the requested type.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains single-versus-array forms, construction, destruction, and undefined behavior, but does not develop modern ownership management.
Examples
Demonstrates a Buffer object, a dynamically sized score array, and incorrect allocation-size and deletion-form choices.
What it assumes
Assumes basic C++ pointers and arrays while teaching runtime-sized allocation and matching release forms.
What you can do after
Apply correctly paired new and delete forms when allocating single objects or arrays.
How it connects
Connects new operator with delete operator, arrays, constructors, destructors, dynamic memory allocation, and std::vector.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.