On this page
  1. Tutorial: RAII & Rule-of-Zero Resource Wrapper
  2. Goal
  3. Compile & Run
  4. Complete Pure-STL Example
  5. Key Takeaways

Tutorial: RAII & Rule-of-Zero Resource Wrapper

Prev: tutorials | Up: tutorials | Next: Ranges & Span Data Pipeline
Rel: RAII & Destructors, std::unique_ptr, Value Categories & Move Semantics
Ref: cppreference — std::unique_ptr
Tags: #public #prog #cpp #tutorial #raii #tier/core


Goal

Wrap a raw C FILE* handle inside a move-only C++ class using std::unique_ptr with a custom deleter—achieving Rule of Zero (no hand-written destructor, move constructor, or move assignment) and zero runtime overhead.

Compile & Run

clang++ -std=c++20 -O2 -Wall -Wextra -fsanitize=address,undefined raii_file.cpp -o raii_file && ./raii_file

Complete Pure-STL Example

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>

struct FileCloser {
    void operator()(std::FILE* f) const noexcept {
        if (f) std::fclose(f);
    }
};

class ScopedFile {
    std::unique_ptr<std::FILE, FileCloser> handle_;

public:
    ScopedFile(const char* path, const char* mode)
        : handle_(std::fopen(path, mode)) {
        if (!handle_) {
            throw std::runtime_error(std::string("Failed to open: ") + path);
        }
    }

    // Rule of Zero: destructor and move operations are automatically generated!
    void write_line(std::string_view line) {
        std::fwrite(line.data(), 1, line.size(), handle_.get());
        std::fputc('\n', handle_.get());
    }
};

int main() {
    {
        ScopedFile f("/tmp/cpp_raii_demo.txt", "w");
        f.write_line("Deterministic cleanup with zero boilerplate.");
    } // std::fclose() runs automatically here

    std::cout << "File written and closed cleanly.\n";
    return 0;
}

Key Takeaways

Linked from

Related notes