C++
Beginner
1 min read
Stack vs Heap and RAII
Example
#include <iostream>
#include <fstream>
#include <stdexcept>
// RAII file wrapper
class FileHandle {
public:
explicit FileHandle(const char* path, const char* mode) {
file_ = std::fopen(path, mode);
if (!file_) throw std::runtime_error("Cannot open file");
std::cout << "File opened\n";
}
~FileHandle() {
if (file_) {
std::fclose(file_);
std::cout << "File closed\n"; // always runs
}
}
// Prevent copy
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
FILE* get() const { return file_; }
private:
FILE* file_;
};
// RAII mutex simulation
struct MutexLock {
explicit MutexLock(bool& mutex) : mutex_(mutex) {
mutex_ = true;
std::cout << "Lock acquired\n";
}
~MutexLock() {
mutex_ = false;
std::cout << "Lock released\n";
}
bool& mutex_;
};
int main() {
bool mutex = false;
{
MutexLock lock(mutex);
std::cout << "Critical section\n";
// lock released automatically at end of block
}
// FileHandle example (file may not exist in demo)
try {
FileHandle fh("demo.txt", "w");
std::fputs("Hello RAII\n", fh.get());
// file closed automatically even if exception thrown
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << "\n";
}
return 0;
}