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.

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

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

How deep it goes
Explains scalar and array allocation through code examples, but does not descend into allocation internals.
Examples
Contrasts malloc-based double and Buffer allocation with corrected new expressions, and demonstrates a score array with mismatched and matched deletion.
What you can do after
Diagnose allocation-size and deallocation-form mismatches, and pair scalar or array new expressions with the appropriate cleanup.
How it connects
Connects new to malloc and free, constructors and destructors, delete, 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.