The new expression and delete manage the heap memory in C++. The new asks the operating system for a block of memory at run time and it gives back a pointer to it, and delete hands that block back. The size does not have to be known when the program is compiled, which is the whole point, and the responsibility for releasing it is entirely yours. Modern C++ prefers to automate that job, but you need to understand the manual form first.
This is the first lesson in the Memory and Smart Pointers module, and the next lesson in this module is about "Why Do unique_ptr and shared_ptr Replace Manual delete?".
new allocates, delete releases
The new expression allocates the memory and it gives back a pointer to the first element. The delete releases it.
#include <iostream>
int main() {
int* buffer = new int[5];
for (int i = 0; i < 5; ++i) {
buffer[i] = (i + 1) * 10;
}
for (int i = 0; i < 5; ++i) {
std::cout << "buffer[" << i << "] = " << buffer[i] << '\n';
}
delete[] buffer;
buffer = nullptr;
return 0;
}The output shows the five values that were written and then read back.
buffer[0] = 10
buffer[1] = 20
buffer[2] = 30
buffer[3] = 40
buffer[4] = 50And the delete[] form has to match the new[] form. Writing a delete where you wrote a new with the brackets is undefined behaviour, and so is the other way round.
The matching forms
what you allocated what you release
---------------------------- ---------------------------------
new T delete
new T[n] delete[]
new T[n] with a placement new an explicit destructor call
nothing at all nothing, the type manages its own memory
#include <iostream>
#include <string>
int main() {
int* single = new int(42);
std::cout << "single: " << *single << '\n';
delete single;
int* array = new int[3]{7, 8, 9};
std::cout << "array: " << array[0] << ' ' << array[2] << '\n';
delete[] array;
std::string* text = new std::string("dynamically allocated");
std::cout << "text: " << *text << '\n';
delete text;
return 0;
}The output shows all three of the allocations behaving correctly.
single: 42
array: 7 9
text: dynamically allocatedAnd notice that a class type that is allocated with new has its constructor called, and delete calls its destructor.
The new and delete operators
The new and delete are operators, and you can replace them for a whole class. That is how a class can keep track of how much memory it has allocated.
#include <cstddef>
#include <iostream>
class TrackedBuffer {
public:
explicit TrackedBuffer(std::size_t count) : count_(count) {
data_ = new int[count];
++live_buffers_;
}
~TrackedBuffer() {
delete[] data_;
--live_buffers_;
}
int* data() { return data_; }
std::size_t count() const { return count_; }
static int live_buffers() { return live_buffers_; }
private:
int* data_;
std::size_t count_;
static int live_buffers_;
};
int TrackedBuffer::live_buffers_ = 0;
int main() {
{
TrackedBuffer first(4);
TrackedBuffer second(8);
std::cout << "live buffers: " << TrackedBuffer::live_buffers() << '\n';
}
std::cout << "after scope: " << TrackedBuffer::live_buffers() << '\n';
return 0;
}The output shows the count going up and then coming back down.
live buffers: 2
after scope: 0Overriding the class level operator new and operator delete is the mechanism behind the pooled allocators, and it is also a neat way to count the allocations in a test.
Forgetting to delete leaks memory
Memory that is allocated and never released is a leak. The program keeps working, but the memory that it took is never returned to the system.
#include <iostream>
int* make_buffer() {
int* buffer = new int[100];
buffer[0] = 1;
return buffer; // the caller never sees the pointer
}
int main() {
for (int i = 0; i < 1000; ++i) {
int* leaked = make_buffer();
std::cout << "iteration " << i << '\n';
if (i == 2) {
break;
}
delete leaked;
}
return 0;
}Each call to make_buffer allocates a hundred integers that are never freed. The program does not crash and the output looks normal, which is exactly what makes the leaks hard to notice.
And the fix is to return the ownership explicitly, with a smart pointer or with a reference to memory that the caller already owns.
The correct order of destruction
The memory has to be released in the reverse order of the allocation. When you allocate several objects, the last one that was allocated is the first one that is destroyed.
#include <iostream>
int main() {
int* first = new int(1);
int* second = new int(2);
int* third = new int(3);
std::cout << "values: " << *first << ' ' << *second << ' ' << *third << '\n';
delete third;
delete second;
delete first;
return 0;
}The order rarely matters for plain integers, but it matters a great deal when the allocations depend on each other.
Placement new
Sometimes you want to construct an object in memory that you already have. The placement new does that. It takes an address instead of allocating.
#include <iostream>
#include <new>
#include <string>
int main() {
alignas(std::string) char storage[64];
std::string* text = new (storage) std::string("placed in existing storage");
std::cout << "text: " << *text << '\n';
text->~basic_string();
return 0;
}The output shows the string constructed in the local storage.
text: placed in existing storageAnd because the destructor was not called automatically, you have to call it explicitly. The placement new appears in the fixed-size buffers, in the containers that manage their own storage, and in the code that wants an object at a known address.
Why manual new and delete are discouraged
The pairing rules are easy to state and easy to break. A leak, a double free, or a delete on memory that was never allocated are all undefined behaviour, and all of them can hide until much later. The smart pointers in the standard library solve the problem by making the compiler enforce the pairing.
#include <iostream>
#include <memory>
int main() {
auto buffer = std::make_unique<int[]>(100);
for (int i = 0; i < 100; ++i) {
buffer[i] = i;
}
std::cout << "last value: " << buffer[99] << '\n';
return 0;
}The output shows the same result with no delete anywhere.
last value: 99Quick reference
- The new T allocates one object and the new T[n allocates an array. Pair them with delete and with delete[ ].
- Forgetting to delete leaks the memory, and deleting twice is
undefined behaviour. - The class level
operator newandoperator deletelet a type customise the allocation. - The placement new constructs an object in memory that you already own, and you have to call the destructor yourself.
- Release the allocations in the reverse order of their creation.
- Prefer
std::make_uniqueandstd::make_sharedto a raw new.
Try it yourself: allocate an array of a size that is read from a variable, fill it, print it and free it. Then deliberately remove the delete and build the program with -fsanitize=address so that you can see the leak reported at the exit. Finally, replace the raw pointer with a std::unique_ptr and confirm that the sanitizer is quiet.