Um momento
0x70Lesson 8 of 9

Manage resources with RAII

Use object lifetime and smart pointers instead of manual ownership.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Explain RAII and choose between values, std::unique_ptr, and shared ownership.

RAII (resource acquisition is initialization) ties a resource’s lifetime to an object’s lifetime. When the object leaves scope, its destructor releases owned resources, including during exception unwinding. Prefer ordinary values and standard containers. Use std::unique_ptr for exclusive dynamic ownership, and use std::shared_ptr only when ownership is genuinely shared; raw pointers and references are usually non-owning views.

main.cpp · C++20
1#include <iostream>
2#include <memory>
3
4int main() {
5    auto score = std::make_unique<int>(100);
6    std::cout << *score << "\n";
7}
Output
100

std::unique_ptr cannot be copied because there should be only one owner; ownership can be transferred with std::move. In most application code, a local vector or string is simpler than allocating a raw array with new.

Key takeaways

  • Prefer values and standard containers first.

  • Use RAII to tie cleanup to object lifetime.

  • Prefer unique ownership unless shared ownership is required.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C++

Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.

Exercise 1

Own a value with a smart pointer

+25 XP

Create an int with std::make_unique, read a replacement value into it, and print Value: N. Do not use raw new.

  • Replace the value
main.c
Loading editor…

Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: