One ownership rule
RAII means Resource Acquisition Is Initialization. Put the resource inside an object, acquire it in the constructor, and release it in the destructor.
The resource can be a file, socket, database handle, mutex lock, heap buffer, or any thing that must be closed, unlocked, or freed.
Why it matters
In hackathon code, crashes often come from cleanup being skipped after an early return or error. RAII makes cleanup happen when the object goes out of scope.
You already use RAII when you use std::string, std::vector, std::ifstream, and std::lock_guard. They clean themselves up without you calling free or close in many places.
Small file wrapper
This class owns a C FILE pointer. It opens the file in the constructor and closes it in the destructor.
Copying is disabled because two objects closing the same file would be unsafe. Move semantics comes next lesson, so keep this simple for now.
#include <cstdio>
#include <stdexcept>
#include <string>
class FileReader {
FILE* file;
public:
explicit FileReader(const std::string& path) : file(std::fopen(path.c_str(), "r")) {
if (!file) {
throw std::runtime_error("Could not open file: " + path);
}
}
~FileReader() {
if (file) {
std::fclose(file);
}
}
FileReader(const FileReader&) = delete;
FileReader& operator=(const FileReader&) = delete;
int getChar() {
return std::fgetc(file);
}
};
int main() {
FileReader input("sample.txt");
int ch = input.getChar();
return 0;
}Design the class
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Common bad pattern
Do not make users remember to call cleanup manually. Someone will return early during a contest fix and forget it.
If your class has open(), close(), and no destructor doing cleanup, it is not protecting the rest of your code.
void process() {
FILE* f = std::fopen("data.txt", "r");
if (!f) return;
// Bug risk: any early return before fclose leaks the file handle.
if (someCondition()) return;
std::fclose(f);
}Prefer existing RAII
Before writing your own RAII class, check if the standard library already has one. Use std::ifstream for files, std::vector for dynamic arrays, std::unique_ptr for single ownership, and std::lock_guard for locks.
Write your own wrapper only when your project uses a C library, system handle, or custom resource that the STL does not already manage.
README proof
For your HackIndia repo, explain one class that manages ownership. Mention what it owns, where it acquires the resource, where it releases it, and why copying is disabled or safe.
This is useful for internships because it shows you can write C++ that survives errors, not just pass sample test cases.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done