Reply to post:

Rust never sleeps: C++-alike language tops Stack Overflow survey for fourth year in a row

DrXym

Objects only clean up after themselves only if you actually remember to destroy them so their destructor is invoked. Scoped and shared pointers help but they're not some panacea.

And RAII is great and all but imagine this scenario - I write a C++ class which wraps a C library, e.g. libjpeg. The constructor loads the JPEG and the destructor frees the buffer up. Simple right?

Now imagine I use a local instance of this class to load the JPEG and push the variable onto a vector. Oh dear my code just crashed. Why? Because my local variable went out of scope and cleaned up the JPEG but the copy in the vector also points to the same data so it will crash when it is accessed or when the vector is destroyed.

So now I have to implement a copy constructor that says what to do if two objects exist pointing to the same data. Maybe I refcount the data and release it on the last reference, or maybe I make copies on a copy. Maybe I need copy on write behaviour in case one object modifies the data. Ah but copy constructor also has to copy I assign a variable to itself so it doesn't blow up. And C++ says if you override the destructor or the copy constructor then you should also override the copy assignment operator too. But wait! C++11 also says you should override the move constructor and move assignment operator too. So potentially have to write 5 functions by hand to stop my simple wrapper from crashing.

But that's not all - now someone wants to inherit my class and my destructor wasn't virtual. So now my code has the potential to leak because the destructor wasn't called. And I might have lifetime issues if the libjpeg is shutdown while I still have instances of my class floating around.

So this simple RAII object can be a goddamned mess. Yes I could write code to account for all these scenarios, or perhaps disable copying by inheriting from a noncopyable class but in the real world, these kind issues are the sort of thing that makes C++ a source of so many bugs.

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon