Skip to content

Ownership and Automatic Cleanup

The Course
•
35 min study

Every object in a program takes up memory, and that memory has to be given back at some point. In some languages a background process cleans up eventually; in older C-style code the programmer frees each block by hand, and forgetting causes leaks while freeing too early causes crashes. C++ takes a third approach: an object's cleanup is tied to its lifetime, and for a local variable the lifetime ends at a precise, predictable moment, the closing brace of the block that declared it.

An object's lifetime determines when it can be used. A local std::vector and the strings inside it own their storage, and when the vector's lifetime ends, its destructor runs and releases that storage automatically. This is scope-based resource management, usually called RAII. You do not need new or delete anywhere in this course's programs. The flip side is that you must never use an object after its lifetime has ended, and the most common way to do that by accident is through a reference.

Predict and run

Predict before running C++
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> make_titles() {
    std::vector<std::string> result{"Read", "Practice"};
    return result;
}

int main() {
    std::vector<std::string> titles = make_titles();
    titles.push_back("Review");
    for (const std::string& title : titles) {
        std::cout << title << "\n";
    }
    return 0;
}
Check your prediction
Text
Read
Practice
Review

result is local to make_titles, so its lifetime ends when the function returns. Returning it by value hands its contents to the caller before that happens, and titles becomes the new owner. The caller receives a complete, valid vector that it can grow and read for as long as it likes.

Watch lifetimes end

You can see the moment cleanup happens by giving a type a destructor, a special function named with a ~ that runs automatically when an object's lifetime ends. The standard types have destructors that free memory; this one just prints.

Destructors run at the closing brace C++
#include <iostream>
#include <string>

struct Noisy {
    std::string name;
    ~Noisy() {
        std::cout << "end " << name << "\n";
    }
};

int main() {
    Noisy outer{"outer"};
    {
        Noisy first{"first"};
        Noisy second{"second"};
        std::cout << "inner block done\n";
    }
    std::cout << "main done\n";
    return 0;
}
Text
inner block done
end second
end first
main done
end outer

Both inner objects ended exactly at the inner closing brace, in reverse order of creation, before main done printed. outer lived until the end of main. No line of code asked for any of this; the compiler inserted the destructor calls where each scope ends. That guarantee is what makes std::string and std::vector safe: their memory is released at the right moment, every time, even when a function returns early.

Never return a reference to a local

Because a local's lifetime ends at its function's closing brace, a reference to it would outlive the object it names:

C++
const std::vector<std::string>& broken_titles() {
    std::vector<std::string> result{"Read"};
    return result;          // dangling: result is destroyed right here
}

Using the returned reference is undefined behavior: the vector and its strings have already been destroyed and their memory released. The compiler warns about this simple case, and a local build with -Werror stops; the browser editor builds without warning flags, so there it may run and print garbage. More complicated versions slip past the warning anyway. Return owning values, like std::vector<std::string>, and the problem cannot arise.

Growth can invalidate references to elements

A vector stores its elements in one block of memory. When push_back needs more room than the block has, the vector allocates a bigger block, moves the elements into it, and releases the old block. Any reference to an element in the old block now dangles:

C++
std::vector<int> plan{25, 10};
int& first = plan[0];
plan.push_back(40);         // may move every element
first = 30;                 // undefined behavior if the elements moved

It may work on one run and corrupt memory on the next, depending on whether the vector happened to have spare room. The fix is about order: finish adding elements first, then take references, or take a fresh reference or a checked index after the last push_back. The planner follows this rule: it only stores references during a loop that does not add or remove tasks.

Practice

Exercise

Your turn

Define Task with a title, minutes and a done flag. Write std::vector<Task> make_plan() that returns two tasks, Read for 20 minutes and Review for 30, both not done. In main, store the result, append Practice for 15 minutes, and only then take a reference to the last task and mark it done. Print:

  • Todo: Read (20 min)
  • Todo: Review (30 min)
  • Done: Practice (15 min)
Your workspace C++
#include <iostream>
#include <string>
#include <vector>

int main() {
    // Define Task and make_plan above main.
    return 0;
}
Hint 1: the idea

The function returns an owning vector by value, with no & in its return type. A reference to an element is safe only after the last push_back.

Hint 2: a first step

Write Task and make_plan first, store the result in main and print the two tasks. When Todo: Read (20 min) and Todo: Review (30 min) appear, add Practice and only then decide which element the reference should name.

Show one solution
Run the solution C++
#include <iostream>
#include <string>
#include <vector>

struct Task {
    std::string title;
    int minutes = 0;
    bool done = false;
};

std::vector<Task> make_plan() {
    return {{"Read", 20, false}, {"Review", 30, false}};
}

int main() {
    std::vector<Task> plan = make_plan();
    plan.push_back({"Practice", 15, false});
    Task& last = plan[plan.size() - 1];
    last.done = true;
    for (const Task& task : plan) {
        std::cout << (task.done ? "Done: " : "Todo: ") << task.title
                  << " (" << task.minutes << " min)\n";
    }
    return 0;
}
Text
Todo: Read (20 min)
Todo: Review (30 min)
Done: Practice (15 min)

make_plan returns an owning vector, so plan in main is a complete object with its own lifetime. The reference last is taken after the final push_back, so no later growth can move the element out from under it, and plan is known to be non-empty at that point, so the index is valid. When main ends, plan is destroyed and every title string is released with it. In the checkpoint you will summarize a vector of tasks without changing it.

Was this article helpful?

Your response is saved on this device.