Free Storage Heap Dynamic Allocation ...

suggest change

The term ‘heap’ is a general computing term meaning an area of memory from which portions can be allocated and deallocated independently of the memory provided by the stack.

In C++, storage obtained through new is commonly called the free store. Implementations often use the process heap for it, but the language does not require the two concepts to be identical.

Areas of memory allocated from the Free Store may live longer than the original scope in which they were allocated. Data too large to be stored on the stack may also be allocated from the Free Store.

Raw memory can be allocated and deallocated by the new and delete keywords.

float *foo = nullptr;
{
    foo = new float; // Allocates memory for a float
    float bar;       // Stack allocated
} // End of bar's lifetime; foo is still in scope

delete foo;          // Destroys the float and frees its memory; foo no longer points at an object
foo = nullptr;       // Setting the pointer to nullptr after delete is often considered good practice

It’s also possible to allocate fixed-size arrays with new and delete, with a slightly different syntax. Array allocation is not compatible with non-array allocation, and mixing the two is undefined behavior. For a type with a non-trivial destructor, the implementation must recover how many elements to destroy; it often stores that count beside the array.

// Allocates memory for an array of 256 ints
int *foo = new int[256];
// Deletes an array of 256 ints at foo
delete[] foo;

When using new and delete instead of malloc and free, a class type’s constructor and destructor run, as they do for an automatic object. That is why new and delete are preferred over malloc and free for class types.

struct ComplexType {
    int a = 0;

    ComplexType() { std::cout << "Ctor" << std::endl; }
    ~ComplexType() { std::cout << "Dtor" << std::endl; }
};

// Allocates memory for a ComplexType, and calls its constructor
ComplexType *foo = new ComplexType();
// Calls the destructor, then frees the memory for the ComplexType object
delete foo;

From C++11 on, the use of smart pointers is recommended for indicating ownership.

C++14 added std::make_unique to the standard library. std::make_unique or std::make_shared is preferred to a naked new and delete. std::make_shared is C++11.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents