Modern C++ / Reference 01

Lifetime and cleanup

Use an object's lifetime to release the resource it owns.

Companion to “Let scope do the cleanup” · C++20

The words

Resource
Something acquired for use that must later be released, such as an open file or allocated memory.
Owner
The object responsible for releasing a resource.
Destructor
The cleanup function called when a class object is destroyed.
RAII: Resource Acquisition Is Initialization
Binding resource management to an object's lifetime so destruction releases what it owns. In the lesson, input owns the file after a successful open.
Scope
The part of the program where a declaration participates in name lookup. A local declaration belongs to its enclosing block.
Lifetime
The period an object exists. For the lesson's class objects, it runs from completed initialization until destruction begins. A resource's lifetime is managed through its owner.

Sources: Core Guidelines, R.1; local declarations.

Rules to use while reading code

The file-reader expressions

ExpressionPurpose and effect
std::ifstream input{path}; Input: file path. Output: a stream object. Side effect: attempts to open for reading; failure sets stream state. Opening.
!input Input: stream state. Output: true when failure is recorded. Side effects: none. State checks.
std::getline(input, line) Input: stream and string. Output: the stream, testable in a condition. Side effects: consumes a line and replaces the string's contents; excludes the newline. Line input.
line.empty() Input: string. Output: true when its length is zero. Side effects: none. Spaces count as characters. Empty check.
std::cout << line << '\n'; Input: string and newline. Output: the output stream. Side effect: writes to standard output.

An empty line contains a newline but no preceding characters; getline succeeds and leaves an empty string. An empty file yields no line. A final text line can succeed without a terminating newline. Extraction rules.

Lesson 01's program contract

The reference program takes one file path and prints its first line plus a newline. It assumes writable standard output.

Exit statusResult
0Printed a line.
1Opening failed.
2No readable line; empty input and read failure are grouped.
64Wrong argument count; usage written to standard error.

The coding exercise changes success to the first nonempty line. If none is extracted, return 2. Keep whitespace significant.