`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.
`delete` — C++ Keyword
The delete keyword in C++: destroys an object and frees memory allocated by new. Also deletes special member functions.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
deleteDestroys an object and releases memory previously allocated with new. Also used as = delete to suppress a special member function.
delete ptr; // destroy object, free memory
delete[] arr; // destroy array, free memory
func() = delete; // prevent calling this function
#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
}
delete on a null pointer is safe and has no effect.delete with new[], or vice versa, is undefined behavior.delete.= delete works on any function, not just special members; use it to prevent undesired overloads.deleteint 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;
}