Pointers/Memory Allocation   «Prev  Next»
Lesson 9 Free store operators
Objective Examine use of the operator new to allocate free store memory

The new operator in C++ 20

In C++20, the terminology has been somewhat refined. The "new operator" is used, but more specifically:

  • new is an operator which involves several steps including:
    • Calling the allocation function (operator new).
    • Constructing the object.

Here's how it works in C++20:

  1. Allocation: The new operator internally calls ::operator new(size_t) (or an overloaded version) to allocate raw memory from the free store.
  2. Construction: After allocation, the object is constructed in that memory location.

So, to directly answer your question:

  • Yes, you can use the new operator in C++20 to allocate memory from the free store. Here is an example:

  • int* p = new int; // Allocates memory for an int and constructs it
    delete p;           // Cleans up the memory
    

Keep in mind:

  • new not only allocates but also constructs the object.
  • For arrays, you would use new[], which has its own deallocation counterpart delete[].

  • int* arr = new int[10]; // Allocates memory for 10 ints and constructs them
    delete[] arr;           // Cleans up the array memory
    

This usage in C++20 remains consistent with previous standards regarding the new operator's functionality for memory allocation on the free store, but with improvements in language features and library support around memory management.

Examine use of the operator new to allocate free store memory

In C++, the operator new is used in the following forms:
  1. new type-name
  2. new type-name initializer
  3. new type-name[expression]
In each case there are at least two effects:
  1. An appropriate amount of store is allocated from free store to contain the named type.
  2. The base address of the variable is returned as the value of the new expression. The operator new returns the value 0 when memory is unavailable. This value should be tested to see if new failed. C++ systems can also throw an allocation exception indicating new failed.

  • Examples The following example uses new:
    int* p, *q;
    p = new int(5);    //allocate and initialize
    q = new int[10];   //q[0] to q[9] with q = &q[0]
    

    In this code, the pointer to int variable p is assigned the address of the store obtained in allocating an object of type int. The location pointed at by p is initialized to the value 5.
    This use is not usual for a simple type such as int, in that it is far more convenient and natural to automatically allocate an integer variable on the stack or globally. More usual is the allocation to the pointer q of an array of elements.

SEMrush Software Target 9SEMrush Software Banner 9