Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I don't think RAII is very nice (python-esque with-statement would be nicer IMO)

You can implement Pythons 'with' statement in C++ with almost the same syntax and exactly the same terseness. This shouldn't be surprising, since C++'s value-semantic constructor-destructor mechanism is simply more general and fundamental.

> copy-assign-move semantics do add a bit of work to every class you introduce.

Only if you fill your objects with multiple dumb C pointers to other objects ad nauseam. If you embrace value semantics and smart pointers you almost never have to write any of the "rule of 5", and when you do it's straightforward. Simple rule: a class should never contain handles or pointers to more than a single resource. Composition handles the rest.



When I mentioned Python's with statement, that's really all I'd want. Something neater than C's "goto error" error handling, but not much more than that. I think there's constructs like this in some languages.

> Simple rule: a class should never contain handles or pointers to more than a single resource. Composition handles the rest.

The issue with this is that in the real world, you have to deal with 3rd party libraries and frameworks or even the OS syscall interface which don't follow this guideline. So you'll end up writing wrappers for all your "foreign" objects from any other libraries you use. This is a lot of work and creates impedance mismatch problems when there's no simple clearly established concept of ownership (e.g. the wrapped objects are already reference counted) or the assumptions of the library aren't friendly to C++ style semantics.

If you live in a "modern C++ only" bubble, this isn't an issue.


Here's an ugly hacked up version of Pythons 'with' statement:

https://gist.github.com/nlyan/7319c7b2a6328460ce9c

As for external libraries...sometimes it requires a bit of ingenuity to find that perfect 'wrap everything!' vs 'write C' balance... but it's usually not so bad if you approach the problem judiciously. unique_ptr and shared_ptr's capabilities are often underestimated in this regard for instance. Both can be used with external reference counting, the former being the most efficient.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: