#include #include #include #include #include #include #include class Scratch { public: explicit Scratch(std::string name) : name_(std::move(name)), file_(std::fopen(name_.c_str(), "w")) { if (!file_) { throw std::runtime_error("could not create " + name_); } std::println(" [open {}]", name_); } ~Scratch() { if (!file_) { return; } std::fclose(file_); std::filesystem::remove(name_); std::println(" [remove {}]", name_); } Scratch(const Scratch&) = delete; Scratch& operator=(const Scratch&) = delete; Scratch(Scratch&& other) noexcept : name_(std::move(other.name_)), file_(std::exchange(other.file_, nullptr)) {} Scratch& operator=(Scratch&&) = delete; void write(const std::string& line) { std::fputs((line + "\n").c_str(), file_); } const std::string& name() const { return name_; } private: std::string name_; std::FILE* file_; }; void report(const std::string& name) { std::println(" {} exists? {}", name, std::filesystem::exists(name)); } void halfway(const std::string& name) { Scratch work(name); work.write("step one"); report(name); throw std::runtime_error("step two failed"); } Scratch draft(const std::string& name) { Scratch notes(name); notes.write("a draft worth keeping"); return notes; } int main() { std::println("1. A block:"); { Scratch notes("notes.tmp"); notes.write("hello"); report("notes.tmp"); } report("notes.tmp"); std::println("2. An exception:"); try { halfway("work.tmp"); } catch (const std::exception& e) { std::println(" caught: {}", e.what()); } report("work.tmp"); std::println("3. A move:"); std::vector kept; kept.reserve(2); kept.push_back(draft("draft.tmp")); Scratch log("log.tmp"); kept.push_back(std::move(log)); report("draft.tmp"); report("log.tmp"); std::println("4. The end of main:"); } /* Try this next... 1. Add the line `Scratch copy = kept[0];` to main and compile. Read the first error. Then delete the line `Scratch(const Scratch&) = delete;` and compile again. What would two destructors do with one FILE*? 2. In main, after `kept.push_back(std::move(log));`, add `log.write("too late");`. It compiles. Run it and read what the sanitizer says, then explain why the compiler had no complaint. 3. Remove `kept.reserve(2);`. Run it again. Count the [remove] lines. When a vector grows it moves its elements; which constructor did it use? 4. Make the destructor print the order things die, then add a second Scratch inside the block in part 1. Which one is removed first, and why is that the safe order? 5. Replace the hand-written class with `std::unique_ptr`. What do you lose, and what did you never have to write? 6. Write a `Timer` that prints how long its scope lasted. It holds no file or memory at all. Is it still a resource? */