Modern C++ / Lesson 01

Let scope do the cleanup

Build a small file reader whose early returns still release the file.

15 to 20 minutes, including exercises · C++20 · Assumes C experience

The idea

Give the file an owner

In C, every exit after a successful fopen needs a route to fclose. In C++, a local class object can do that work: its destructor, the cleanup function called when the object is destroyed, runs when execution leaves its block, including through an early return. Language rule.

An owner is the object responsible for releasing a resource. Here, the resource is an open file, and its owner is an std::ifstream. This is RAII, short for Resource Acquisition Is Initialization: bind resource management to an object's lifetime so destruction releases what it owns. Core Guidelines, R.1.

The technique predates C++11. We start here because it underlies everyday use of modern library types. You can see the same idea in Stroustrup's file-handle example.

Read the code

One file, three return paths

This function prints the first line. A failed file open normally records failure in the stream's state; constructing input does not establish that the file opened. That is why we check !input. File opening; stream state.

// Print the first line of a text file.
// Input: path names the file; standard output is writable.
// Output: 0 for a printed line, 1 for open failure, 2 for no readable line.
// Side effects: reads the file and writes the line plus a newline to standard output.
int print_first_line(const char* path) {
    std::ifstream input{path};
    if (!input) {
        return 1;
    }

    std::string line;
    if (!std::getline(input, line)) {
        return 2;
    }

    std::cout << line << '\n';
    return 0;
}
The working function from first_line.cpp. That file also contains the headers and main.
ExpressionRead it as
std::ifstream input{path}; Declare input; braces initialize it with path. std:: selects a name from the standard-library namespace.
std::string line; Construct an empty string that manages its character storage.
std::getline(input, line) Read into line, growing it as needed; discard the newline. Test the returned stream to see whether extraction succeeded. Line input.
std::cout << line << '\n'; Write the text and a newline to standard output.

At either return after line's declaration, destruction runs in reverse construction order: line, then input. The stream's owned file buffer closes the file during destruction. At return 1, only input has been constructed, and no file opened successfully. Destruction order; file cleanup.

How far does the cleanup guarantee go?

It applies on normal scope exit and during stack unwinding, the destruction performed as an exception travels toward a handler. Abnormal process termination does not guarantee this cleanup. We'll study exceptions separately. Unwinding rules.

Try it

Compile and read a line

Do exercise 1's prediction first. Then run these commands from a terminal:

cd '/home/dmedeiros/Documents/ChatGPT/Teach me C++'
mkdir -p build
g++ -std=c++20 -Wall -Wextra -Wpedantic \
    exercises/0001-scope-cleanup/first_line.cpp \
    -o build/first-line
./build/first-line exercises/0001-scope-cleanup/notes.txt
echo $?

Expected output:

compile the tool
0

main requires exactly one path argument. These are the program's exit statuses:

StatusMeaning
0Printed a line, including an empty line.
1Could not open the file.
2No readable line: empty file or failed input.
64Wrong argument count; usage goes to standard error.

This exercise assumes writable standard output. Status 2 deliberately groups empty input and read failure; fuller error reporting comes later.

Practice

Make the cleanup reasoning yours

1. Predict before running

Consider a missing file, an empty file, and a readable file containing one line of text. For each, name the status, the local class objects that get constructed, their destruction order, and whether a file was open. Write your answers before revealing the check.

Check your prediction
InputStatus Objects and cleanup
Missing file1 Construct and destroy input only. No file opened.
Empty file2 Construct input, then line. Destroy line, then input; the open file closes.
One text line0 Same construction and destruction order as the empty file. Print the line before cleanup.

The return 2 path needs no special cleanup branch. Check the lifetime rule.

2. Skip empty lines

Edit exercise.cpp to print the first nonempty line. Empty means zero characters: spaces and tabs count as content. A final line without a newline must work too.

Keep statuses 0, 1, and 64. Return 2 if no nonempty line is extracted, including an empty file or a file containing only empty lines. Use std::getline and line.empty(); add no manual close, free, new, or delete.

Run the checks from the workspace root; they compile your source automatically:

python3 -m unittest discover \
    -s exercises/0001-scope-cleanup \
    -p 'test_exercise.py' -v

The starter intentionally fails the leading-empty-lines and all-empty-lines cases. The other checks pass. The checks assess output and exit status; your explanation and a source review establish how cleanup works.

Show a hint, without the solution

Use a while condition that calls std::getline(input, line). Inside the loop, line.empty() tells you whether the extracted string has zero characters. Decide where a successful return belongs, and what should happen when the loop ends. The empty check.

For a manual trial, leading-empty.txt starts with two empty lines; your completed program should print keep this line.

3. Explain it from memory

Close the lesson. Explain why an early return can be safe here, and what would differ if input were a raw FILE* returned by fopen. At the start of your next session, try that explanation again before reopening your notes.

Read one rule

Read C++ Core Guidelines, R.1, including its examples. Focus on which object releases each resource; unfamiliar syntax can wait. Keep the lifetime reference for lookup.