Lesson content
Read, practise, then check your understanding
Automatic objects are destroyed when their scope ends. Dynamic storage lasts until its owner releases it, which is useful when size or lifetime is not known locally. A new expression allocates and constructs; delete destroys and deallocates. Arrays require matching new[] and delete[].
int* number = new int{42};
delete number;
number = nullptr;
int* values = new int[3]{1, 2, 3};
delete[] values;
Mismatched deletion, double deletion, leaks, and use-after-free are serious defects. Allocation can throw std::bad_alloc. Manual code becomes especially fragile across early returns and exceptions.
Prefer RAII ownership
#include <memory>
#include <vector>
auto item = std::make_unique<int>(42);
std::vector<int> values{1, 2, 3};
RAII binds a resource to an object whose destructor releases it. std::vector owns variable-size arrays; std::string owns text; std::unique_ptr owns one dynamic object. These types make cleanup deterministic and exception-safe.
Use std::make_unique rather than a visible owning new. Use std::shared_ptr only when ownership is truly shared, not simply to avoid deciding who owns an object. Raw pointers and references remain useful as non-owning views. The Rule of Zero says a class composed of RAII members should usually declare no custom destructor, copy operation, or move operation.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.