Hacker News new | ask | show | jobs
by jefbyokyie 534 days ago
> number 1 issue I find myself having when switching from C++ to C is missing RAII

That's because you've become complacent; you've gotten used to the false comfort of destructors. C++ destructors promise that you can ignore object destruction in business logic, and that's a false promise.

Assume you have a function that already has a correct traditional (cascading gotos, or arrow pattern) exit path / error path. Assume that you have the (awkward) defer-based implementation of the same function. Assume you need to insert a new construction step somewhere in the middle. In the defer-based implementation, you insert both the new action and its matching "defer" in the same spot.In the traditional implementation, you locate the existent construction steps between which you insert the new construction step; you locate the corresponding existent destruction steps (which are in reverse order), and insert the new destruction step between them. The thinking process is more or less the same, but the result differs: without defer, your resultant source code shows what will actually happen on the exit path, and in precisely what order, and you can read it.

I think defer is awful.

1 comments

See but the issue is that humans are not perfect, and time is usually a resource.

Without defer like mechanisms objects get leaked, mutexes held after return, etc...

In a perfect world everything could be perfectly explicit as infinite time and energy has gone into ensuring nothing is forgotten and everything / every code path is well exercised.

Even then, scoped based resource acquisition / releasing still feels more ergonomic to me.