In general, you should prefer allocating memory on the stack when possible. Stack allocation is faster and automatically managed.
Use stack allocation when:
Use heap allocation when:
Here's an example illustrating both:
#include <iostream>
void func() {
// Allocated on the stack
int stackInt = 10;
// Allocated on the heap
int* heapInt = new int(20);
// We must delete the heap-allocated variable
delete heapInt;
} // stackInt is automatically deallocated here
int main() {
int size;
std::cin >> size;
// Size not known at compile time
int* array = new int[size];
delete[] array;
}
Remember, whenever you allocate memory on the heap with new
, you are responsible for deallocating it with delete
to avoid memory leaks.
In modern C++, you can often avoid making this decision by using standard library containers like std::vector
, or smart pointers like std::unique_ptr
and std::shared_ptr
. These manage memory for you, with the memory for the actual data being allocated on the heap, but the bookkeeping handled automatically.
Answers to questions are automatically generated and may not have been reviewed.
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete