Pointers/Memory Allocation   «Prev  Next»
Lesson 9 Free Store Operators
Objective Understand the use of new for dynamic memory allocation and modern alternatives in C++

The new Operator in Modern C++

In C++, the new operator requests memory from the free store (commonly referred to as the heap) and constructs an object in that memory. It combines two steps: allocation and construction. However, modern C++ encourages developers to use RAII principles and smart pointers to avoid manual memory management whenever possible.

How new Works

  1. Allocation: Calls ::operator new(size_t) or an overloaded version to reserve raw memory.
  2. Construction: Invokes the constructor to initialize the object within that memory block.

int* p = new int(42);  // Allocates and constructs an int
delete p;              // Destroys and frees the memory

Using new[] for Arrays

When allocating arrays, use new[] with a matching delete[]:


int* arr = new int[5];   // Allocates 5 ints
delete[] arr;            // Correctly frees the array

⚠️ Mixing malloc/free with new/delete is undefined behavior in C++.

Error Handling in Allocation

In older C++ standards, new returned 0 (null) on failure. In modern C++, allocation failures throw std::bad_alloc unless you explicitly request a nothrow version:


int* p = new(std::nothrow) int(10);
if (p == nullptr) {
    std::cerr << "Memory allocation failed\n";
}

Preferred Modern Approach: Smart Pointers

Instead of manually managing memory with raw new and delete, use smart pointers from the C++ standard library:


#include <memory>

auto ptr = std::make_unique<MyClass>();   // Exclusive ownership
auto sp  = std::make_shared<MyClass>();   // Shared ownership

Smart pointers automatically release resources when they go out of scope, greatly reducing the risk of memory leaks and dangling pointers.

Summary of new Forms

Syntax Description
new TypeName Allocates and default-constructs a single object
new TypeName(initializer) Allocates and constructs using the initializer or constructor
new TypeName[expression] Allocates an array of objects
Diagram showing the difference between new, new[], and smart pointers.
Diagram showing the difference between new, new[], and modern smart pointers.

Best Practices


SEMrush Software Target 9SEMrush Software Banner 9