Lesson 9 | Free Store Operators |
Objective | Understand the use of new for dynamic memory allocation and modern alternatives in C++ |
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.
new
Works::operator new(size_t)
or an overloaded version to reserve raw memory.
int* p = new int(42); // Allocates and constructs an int
delete p; // Destroys and frees the memory
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++.
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";
}
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.
new
FormsSyntax | 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 |
new
, new[]
, and modern smart pointers.
std::unique_ptr
and std::shared_ptr
instead of raw new
in most cases.new
, always pair it with the correct form of delete
.