/** * @file raii.cpp * @author Jeffrey Bergamini for CS 19 Boot Camp, jeffrey.bergamini@cabrillo.edu * * RAII: "Resource acquisition is initialization" * Perhaps easier to understand: "scope-based resource management" * * An object's resources (memory storage, file handles, etc.) are allocated during initialization, * and released during destruction. When an object's lifetime ends, its resources should be * deallocated/cleaned up/closed/etc. * * We'll run this through `strace` to verify when files are opened/closed: * strace --trace=openat,close ./a.out #include #include // Counts and returns the number of English vowel characters in an input stream. size_t count_vowels(std::istream &source) { size_t vowel_count = 0; for (char c; source >> c;) { c = std::tolower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ++vowel_count; } return vowel_count; } int main() { std::ifstream hamlet{"/srv/datasets/shakespeare-hamlet.txt"}; // Preview of subtype polymorphism: A `std::ifstream` *is a* `std::istream` // (i.e., an input stream reading from a file is a specific kind of input stream) std::cout << "Hamlet: " << count_vowels(hamlet) << '\n'; std::cout << "Hamlet again: " << count_vowels(hamlet) << '\n'; { std::ifstream macbeth{"/srv/datasets/shakespeare-macbeth.txt"}; std::cout << "Macbeth: " << count_vowels(macbeth) << '\n'; // Lifetime of `macbeth` ends here. File will be closed. } std::ifstream othello{"/srv/datasets/shakespeare-othello.txt"}; std::cout << "Othello: " << count_vowels(othello) << '\n'; // std::cin is just a plain input stream: std::cout << "std::cin: " << count_vowels(std::cin) << '\n'; // Lifetimes of `hamlet` and `othello` end here. // Will be closed in the opposite order of initialization (`othello`, then `hamlet`) }