AlienRobot 1 day ago

I'm not very good with C++, so one time I tried to use RAII to do all sorts of neat GUI things, like freeze property events and ref count uses of files to know when to freed them from memory.

Essentially instead of doing

    object.freeze();
    object.setProperties(...);
    object.thaw();
I tried to do

    {
        Freezer freezer(object);
        object.setProperties(...);
    }
EVERY time I need a start/end matching function I used RAII instead because it looked neat. I tried to make "with" from Python in C++.

The problem is that exceptions thrown in a destructor can't be caught, which made this coding style practically impossible to use. Thawing the properties meant dispatching property change events, which meant that event handlers all around the app would be executed inside a destructor unaware that they were being executed inside a destructor. If any of these threw an exception, the whole thing crashed. In hindsight dispatching these events from a setter instead of from the main event loop also creates all sorts of trouble.

1
int_19h 15 hours ago

The closest equivalent to `with` from Python would be a higher-order function defined such that it can accept a lambda (i.e. it needs to be a template). Then you'd write something like:

   object.batchEvents([&]{
     object.setProperties(...);
   });
(for bonus points, pass object reference as argument to the lambda)