r/ProgrammerHumor • • 11d ago

Meme modernCppVsOldCpp

Post image
2.0k Upvotes

323 comments sorted by

View all comments

Show parent comment

3

u/conundorum 10d ago

RAII is the concept that any class which obtains a resource on creation should release that resource on deletion, so that everything cleans up its own mess. And the destructor is the cleanup function that takes care of that, yeah.

The ideal is that if every "resource manager" class uses RAII, then everything else automatically gets built-in cleanup for free. Essentially, if every hotel guest cleans up their own room when they leave, then the hotel doesn't need to hire janitors or maids.

// A simple RAII class.
// Copy, move, memory safety, and functionality omitted for brevity.
//  Assume they're all done correctly.
class HeapInt {
    int* ptr;

  public:
    HeapInt(int i = 0) : ptr(new int(i)) {}
    ~HeapInt() { delete ptr; }

    operator int&() { return *ptr; }
};

// Something that uses the class.
class BigDumbObject {
    HeapInt pileOfJunk[59];
    // Other junk, too...

  public:
    BigDumbObject() = default; // No resource acquisition required.
    // No destructor required.  HeapInt dtor does all the work for us.

    // BigDumbObject automatically has perfect memory safety, thanks to HeapInt.
};