Curriculumstd::unique_ptr
std::unique_ptr
A <code>std::unique_ptr</code> is a Smart Pointer. It acts exactly like a normal pointer, but with a superpower: when the pointer goes out of scope and is destroyed, it automatically calls <code>delete</code> on the heap memory it owns. No more memory leaks!
01Creating a unique_ptr
Instead of
Notice that we never call
new, we use std::make_unique. Notice that we never call
delete. When main() ends, the pointer on the stack is destroyed, which triggers an automatic cleanup of the heap memory!main.cpp
Terminal
Waiting for execution...
Visualizer
Click Run to see memory state
02Exclusive Ownership (No Copies)
Because it is a unique pointer, it demands exclusive ownership of the memory.
If you try to copy it into another variable, the C++ compiler will throw a massive error. Two pointers cannot exclusively own the same memory!
If you try to copy it into another variable, the C++ compiler will throw a massive error. Two pointers cannot exclusively own the same memory!
main.cpp
Terminal
Waiting for execution...
03Transferring Ownership (std::move)
If you can't copy it, how do you give it to someone else? You move it using
This explicitly strips ownership from the first pointer and gives it to the second. The first pointer becomes a
std::move.This explicitly strips ownership from the first pointer and gives it to the second. The first pointer becomes a
nullptr.main.cpp
Terminal
Waiting for execution...
Visualizer
Click Run to see memory state
04Passing to Functions
How do you pass a
If the function just needs to read or modify the data without taking ownership, pass the underlying raw pointer using
unique_ptr to a function? If the function just needs to read or modify the data without taking ownership, pass the underlying raw pointer using
.get().main.cpp
Terminal
Waiting for execution...
05Custom Objects & Destructors
Smart pointers shine when dealing with complex objects.
When the smart pointer goes out of scope, it automatically calls the object's Destructor before freeing the memory.
When the smart pointer goes out of scope, it automatically calls the object's Destructor before freeing the memory.
main.cpp
Terminal
Waiting for execution...
AI Tutor
In modern C++ (C++11 and onwards), you should almost never use raw 'new' and 'delete'. Smart pointers make memory management 100% safe and automatic.