Lesson 9 | Free store operators |
Objective | Examine use of the operator new to allocate free store memory |
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:
operator new
).Here's how it works in C++20:
new
operator internally calls ::operator new(size_t)
(or an overloaded version) to allocate raw memory from the free store.So, to directly answer your question:
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.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.
new
is used in the following forms:new
type-namenew
type-name initializernew
type-name[
expression]
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.
new
:
int* p, *q; p = new int(5); //allocate and initialize q = new int[10]; //q[0] to q[9] with q = &q[0]
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.
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.