Modern C++ – RAII

https://news.ycombinator.com/rss Hits: 2
Summary

Modern C++ What is RAII? Naive implementation Understanding the problem The fix — rule of 3 Nice wrapper — Rule of 5 Implications — rule of zero Limitations Further reading Modern C++ — RAII Modern C++ embraces the features from C++11 which lay the foundation for a new generation of C++. It introduced move semantics and embraced RAII in the standard library (unique_ptr, shared_ptr, lock_guard). Embracing Resource Acquisition Is Initialization (RAII) makes C++ the safest, most productive and fun C++ has ever been. Unfortunately, to leverage RAII, you need a good understanding of why it's needed and how it works which is what I hope to distill for you. I'll explain RAII by example while referencing the C++ core guidelines. What is RAII? The idea behind RAII is to manage resources using variables and scope so that resources are automatically freed. A resource is anything that can be acquired and must later be released, not just memory. Resource Memory new/delete File descriptors open/close Lock lock/unlock The main idea is to acquire a resource and store its handle in a private member in a class. We can then control its access and release the resource in the destructor. We'll create a safe wrapper around a UNIX file descriptor keeping in mind that the same concept can be applied to any other resource. Normally, the standard library has a robust implementation already in place so make sure you check there first to save yourself some work. Naive implementation We'll start off with the following definition and assume that there's a reasonable implementation for each prototype. class NaiveFile { public: NaiveFile(const std::string &path); ~NaiveFile(); std::string read_1024() const; private: int fd; }; The following code behaves in ways that are unintended: void accidental_copy(NaiveFile file); int main() { NaiveFile naive_file = NaiveFile(filename); accidental_copy(naive_file); auto file2 = naive_file; } Running the above code with trace printing results in the following:...

First seen: 2025-05-30 10:23

Last seen: 2025-05-30 11:23