On this page
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
- Because
FileCloseris an empty stateless struct, Empty Base Optimization makessizeof(ScopedFile) == sizeof(std::FILE*). ScopedFileis automatically move-only and non-copyable becausestd::unique_ptris move-only.
Linked from
Related notes
- tuts/cpp/builtins/raii_and_destructors Linked here; links to this page; shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/tutorials/ranges_and_span_data_pipeline Linked here; links to this page; shared tags: #cpp, #prog, #tier, #tutorial
- tuts/cpp/tutorials Linked here; links to this page; shared tags: #cpp, #prog
- tuts/cpp/language_and_raii/value_categories_and_move_semantics Linked here; shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/stdlib/memory/unique_ptr Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/tutorials/jthread_work_queue_and_atomics shared tags: #cpp, #prog, #tier, #tutorial
- tuts/cpp/builtins/auto shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #cpp, #prog, #tier