Skip to content
← All C++ tracks

RAII: Objects With Lifetimes

C++

Manage resources through object lifetimes. Use constructors and destructors to make cleanup predictable, including when control leaves a scope early.

This track uses C++. You can make it your practice mode to browse related content across the site.

4 exercises

Explore freely. Sign in to keep your progress.

Your learning sequence

  1. 1 Not solved yet. Observe cleanup at the end of a scope Practice · Easy
  2. 2 Not solved yet. Write the guard yourself Practice · Medium
  3. 3 Not solved yet. Let a vector own the histogram buckets Practice · Medium
  4. 4 Not solved yet. Close a transaction when an operation throws Practice · Medium

Check yourself

4 questions · not saved while you're signed out

Use these questions to check your understanding and compare explanations. Your score does not affect track completion.

0 / 4 correct

What destruction order does C++20 guarantee for the two elements when this vector leaves scope?

Choose one answer to reveal the explanations. Answers are kept only while this page is open.

#include <iostream>
#include <vector>

struct Item {
    int id;
    explicit Item(int value) : id(value) {}
    ~Item() { std::cout << id << std::endl; }
};

int main() {
    std::vector<Item> v;
    v.reserve(2);
    v.emplace_back(1);
    v.emplace_back(2);
}
Question 1 of 4