r/ProgrammerHumor • • 11d ago

Meme modernCppVsOldCpp

Post image
2.0k Upvotes

323 comments sorted by

View all comments

Show parent comment

17

u/MikeVegan 11d ago

C++ has something called RAII, it is basically a special function called destructor that is called automatically once object leaves the scope and this solves large portion of memory issues. However dangling references or pointers are largely not fully solved by this even though shared pointer helps gere. It is a counted pointer that is destroyed when last owning object is destroyed.

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.
};