`new` — C++ Keyword

`new` — C++ Keyword

The new keyword in C++: dynamically allocates memory and constructs an object.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

new

Allocates memory from the free store (heap) and constructs an object in that memory. Returns a pointer to the constructed object.

Syntax

Type* ptr = new Type;                    // default-initialize
Type* ptr = new Type(args);              // direct-initialize
Type* ptr = new Type{args};              // list-initialize
Type* arr = new Type[n];                 // array allocation
Type* ptr = new (placement) Type(args);  // placement new

Example

#include <print>
#include <memory>

struct Node {
    int val;
    Node* next;
    Node(int v) : val(v), next(nullptr) {}
};

int main() {
    // Direct allocation and deletion
    Node* n = new Node(42);
    std::println("{}", n->val);
    delete n;

    // Array allocation
    int* arr = new int[5]{1, 2, 3, 4, 5};
    std::println("{}", arr[2]);
    delete[] arr;

    // Prefer smart pointers in production code
    auto p = std::make_unique<Node>(99);
    std::println("{}", p->val);   // auto-deleted when p goes out of scope
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}