Memory management: new, delete, unique_ptr
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function's variables live on the stack and disappear when the function exits. Memory that's needed for longer, or whose size isn't known in advance, is taken from the heap:
int *arr = new int[n]; // allocate n integers
arr[0] = 5;
delete[] arr; // give it back (for an array — delete[], for a single object — delete)
A manual delete is easy to forget (a leak) or to do twice (a crash). That's why in modern C++ owning memory
is left to smart pointers (#include <memory>):
auto p = std::make_unique<int[]>(n); // an array on the heap; it's freed by itself when p goes out of scope
p[0] = 5;
auto hero = std::make_unique<Hero>(); // a single object
This is the RAII principle: a resource belongs to an object, and the object frees it by itself when it's destroyed.
Even simpler is std::vector: it allocates and frees memory by itself.
Task. Read n and n numbers into an array allocated with std::make_unique<int[]>(n). Print the numbers
without repeats, in the order they first appear.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.