Lesson 6 of 7
Mini Project Part 5 - RAII Smart-Pointer File Wrapper
Build a production-quality `FileStream` RAII class that wraps `std::fstream` with a `unique_ptr`-managed internal buffer, demonstrates ownership transfer (movable but not copyable), provides a `BufferedWriter` that shares a file via `shared_ptr`, and shows correct `weak_ptr` use for a file registry that doesn't keep files alive.
FileStream - RAII + Smart Pointer Ownership Hierarchy
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include <stdexcept>
#include <map>
// ── RAII managed file ─────────────────────────────────────────
class ManagedFile {
std::unique_ptr<std::fstream> fs_;
std::string path_;
bool writable_;
public:
ManagedFile(std::string path, bool write_mode)
: fs_(std::make_unique<std::fstream>())
, path_(std::move(path))
, writable_(write_mode)
{
auto mode = write_mode
? (std::ios::out | std::ios::app)
: std::ios::in;
fs_->open(path_, mode);
if (!fs_->is_open()) {
throw std::runtime_error("Cannot open: " + path_);
}
std::cout << "ManagedFile opened: " << path_ << "
";
}
~ManagedFile() {
if (fs_ && fs_->is_open()) {
fs_->flush();
fs_->close();
std::cout << "ManagedFile closed: " << path_ << "
";
}
}
// Movable - transfers ownership of the fstream
ManagedFile(ManagedFile&&) = default;
ManagedFile& operator=(ManagedFile&&) = default;
// Not copyable - one ManagedFile per file handle
ManagedFile(const ManagedFile&) = delete;
ManagedFile& operator=(const ManagedFile&) = delete;
void write(const std::string& data) {
if (!writable_) throw std::runtime_error("File is read-only");
*fs_ << data;
}
std::string read_all() {
fs_->seekg(0);
return std::string(std::istreambuf_iterator<char>(*fs_),
std::istreambuf_iterator<char>());
}
const std::string& path() const { return path_; }
};
// ── Shared ownership - multiple writers to same file ──────────
using SharedFile = std::shared_ptr<ManagedFile>;
class BufferedWriter {
SharedFile file_;
std::vector<std::string> buffer_;
size_t flush_threshold_;
public:
BufferedWriter(SharedFile file, size_t threshold = 3)
: file_(std::move(file)), flush_threshold_(threshold)
{}
void write(const std::string& msg) {
buffer_.push_back(msg);
if (buffer_.size() >= flush_threshold_) flush();
}
void flush() {
for (const auto& s : buffer_) file_->write(s + "
");
buffer_.clear();
std::cout << "Flushed " << buffer_.size() << " items
";
}
~BufferedWriter() {
if (!buffer_.empty()) flush(); // flush on destruction
}
};
// ── File registry - weak_ptr: doesn't keep files alive ────────
class FileRegistry {
std::map<std::string, std::weak_ptr<ManagedFile>> registry_;
public:
void register_file(const SharedFile& f) {
registry_[f->path()] = f; // weak - doesn't own
}
bool is_open(const std::string& path) const {
auto it = registry_.find(path);
if (it == registry_.end()) return false;
return !it->second.expired(); // expired = file was closed
}
};
int main() {
FileRegistry registry;
{
auto file = std::make_shared<ManagedFile>("test_output.txt", true);
registry.register_file(file);
std::cout << "Registry: test_output.txt open? "
<< registry.is_open("test_output.txt") << "
"; // 1
BufferedWriter w1(file);
BufferedWriter w2(file); // share same file
w1.write("Line 1 from w1");
w1.write("Line 2 from w1");
w2.write("Line 3 from w2");
w1.write("Line 4 from w1"); // triggers flush (threshold=3)
// file still open here - shared with w1, w2
} // w1, w2, file all destroyed here
std::cout << "Registry: test_output.txt open? "
<< registry.is_open("test_output.txt") << "
"; // 0 (expired)
return 0;
}Common Mistakes
- Not flushing in destructor - `BufferedWriter` holds unwritten data. If destroyed without explicit `flush()`, data is lost. Always flush in the destructor for write-buffering RAII objects.
- Shared file ownership with one writer closing early - if `BufferedWriter w1` is destroyed and it holds the last `shared_ptr<ManagedFile>`, the file closes before `w2` is done. Ensure all writers share ownership correctly and the file lives as long as the last writer.
- Comparing files by path in registry without normalisation - 'test.txt' and './test.txt' and '/cwd/test.txt' are the same file but different strings. Use `std::filesystem::canonical()` (C++17) to get a canonical path for registry keys.
Tip
Tip
Practice Mini Project Part 5 RAII SmartPointer File Wrapper in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Encapsulating C-style FILE* in std::unique_ptr with a Custom RAII Deleter
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 5 RAII SmartPointer File Wrapper from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project Part 5 RAII SmartPointer File Wrapper is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Build a production-quality `FileStream` RAII class that wraps `std::fstream` with a `unique_ptr`-managed internal buffer, demonstrates ownership transfer (movable but not copyable), provides a `BufferedWriter` that shares a file via `shared_ptr`, and shows correct `weak_ptr` use for a file registry that doesn't keep files alive.
- Not flushing in destructor - `BufferedWriter` holds unwritten data. If destroyed without explicit `flush()`, data is lost. Always flush in the destructor for write-buffering RAII objects.
- Shared file ownership with one writer closing early - if `BufferedWriter w1` is destroyed and it holds the last `shared_ptr<ManagedFile>`, the file closes before `w2` is done. Ensure all writers share ownership correctly and the file lives as long as the last writer.
- Comparing files by path in registry without normalisation - 'test.txt' and './test.txt' and '/cwd/test.txt' are the same file but different strings. Use `std::filesystem::canonical()` (C++17) to get a canonical path for registry keys.
Finished this lesson?