Memory Management in C++

Memory is obtained (from the Operating System) through operators new and new [], and is released through operator delete and delete [].

int * pInt = new int;
MyClass * pObj = new MyClass;

To get an array of int's or of MyClass objects use new []:

int * pArrayOfInt = new int[7];
MyClass * pArrayOfObj = new MyClass[4];

Actually, new not only gets the requested memory (from the Operating System) but also constructs one or so many objects.


Memory is released likewise by means of the delete and delete [] operators:

delete pInt;
delete [] pArrayOfInt;
delete pObj;
delete [] pArrayOfObj;

Note that delete and delete [] take a pointer as their argument.


In the Standard Template Library, memory management is performed by allocators.

Placement new*

// ...

[...]

Writing your own new operators overrides for specific types

// ...

[...]


The STL provides three smart pointers...

std::nullpt (since C++11)

The keyword nullptr denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

The nullptr keyword can be used to test if a pointer or handle reference is null before the reference is used. Function calls among languages that use null pointer values for error checking should be interpreted correctly. You cannot initialize a handle to zero; only nullptr can be used.

...

Here is another, somewhat more sophisticated, sample:

#include <cstddef>
#include <iostream>

template<class T>
constexpr T clone(const T& t)
{
  return t;
}

void g(int*)
{
  std::cout << "Function g called\n";
}

int main()
{
  g(nullptr);        // Fine
  g(NULL);           // Fine
  g(0);              // Fine

  g(clone(nullptr)); // Fine
//  g(clone(NULL));    // ERROR: non-literal zero cannot be a null pointer constant
//  g(clone(0));       // ERROR: non-literal zero cannot be a null pointer constant
}