`new` — C++ Keyword
`new` — C++ Keyword
The new keyword in C++: dynamically allocates memory and constructs an object.
`new` — C++ Keyword
The new keyword in C++: dynamically allocates memory and constructs an object.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
newAllocates memory from the free store (heap) and constructs an object in that memory. Returns a pointer to the constructed object.
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
#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
}
new/delete should be avoided in application code; use std::make_unique / std::make_shared instead.new throws std::bad_alloc; use new (std::nothrow) for a non-throwing version.new[] with array delete[].newint 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;
}