RAII and smart pointers
Let destructors release resources, even when exceptions are thrown.
What you will be able to do
- Use unique_ptr by default for heap ownership.
- Pass unique_ptr by reference or move it; never copy it.
- Do not use shared_ptr to avoid thinking about ownership.
In plain English
RAII ties a resource lifetime to an object lifetime. std::unique_ptr expresses exclusive ownership; std::shared_ptr expresses shared ownership and should be rare. Prefer stack values and containers before reaching for a pointer.
#include <memory>
#include <iostream>
#include <string>
struct Lesson {
std::string title;
};
int main() {
auto lesson = std::make_unique<Lesson>(Lesson{"Pointers"});
std::cout << lesson->title << "\n";
// destroyed automatically at the end of scope
}Your turn
MediumOwn a lesson safely
Create a unique_ptr to a Lesson with the title "RAII" and print the title.
CPP · starter
Lesson* lesson = new Lesson{"RAII"};Check your understanding before moving on.
Knowledge checkQuestion 1
Which smart pointer communicates exclusive ownership?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.