`delete` — C++ Keyword

`delete` — C++ Keyword

The delete keyword in C++: destroys an object and frees memory allocated by new. Also deletes special member functions.

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.

delete

Destroys an object and releases memory previously allocated with new. Also used as = delete to suppress a special member function.

Syntax

delete ptr;          // destroy object, free memory
delete[] arr;        // destroy array, free memory

func() = delete;     // prevent calling this function

Example

#include <print>
#include <stdexcept>

struct Resource {
    int* data;
    Resource(int n) : data(new int[n]{}) {}
    ~Resource() { delete[] data; }          // paired delete[]

    // Prevent copying (= delete)
    Resource(const Resource&)            = delete;
    Resource& operator=(const Resource&) = delete;
};

int main() {
    {
        Resource r(10);
        r.data[0] = 7;
        std::println("{}", r.data[0]);
    }   // destructor runs, delete[] frees memory

    int* p = new int(42);
    std::println("{}", *p);
    delete p;   // free single object

    // Resource r2 = r;   // error: copy constructor is deleted
}

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;
}