3 ms·
This article wonderfully communicates the same feelings I have after writing Rust, and having to write C/C++ for my day job. I regularly encounter situations wh
by thenewwazoo 9y ago
This article wonderfully communicates the same feelings I have after writing Rust, and having to write C/C++ for my day job. I regularly encounter situations where I could do it clearer, safer, or clearer and safer in Rust, but instead I just return a null pointer.
- Asooka 9y agoI have taken to, where possible, using something like this: template <class T> struct Optional { T value; bool hasValue; Optional():empty(false) {} Optional(const T& value):value(value), empty(true) {} // Also T move ctor, copy ctor, etc. }; And I try to make sure that all my structs' "empty" state can be set by memset(0). Pointers are a bit tricky, especially strings, but for them I kind of like this: class MyString { MyBuffer *buf; // Pointer to refcounted shared storage, i.e. CoW string public: const char *cStr() { if (!buf || !buf->chars) { return ""; } else { return buf->chars; } } }; In short, 1. Try to design structs such that they can be memset(0). 2. Try not to return NULL pointers, if possible. Maybe keep static empty instances to return instead of NULL pointers. Of course, the overhead of that approach is not always acceptable, but when it is, I find that it significantly simplifies the code that uses such classes.
- sbmassey 9y agoYou could use boost::optional. Or std::optional, come c++17.
- thenewwazoo 9y agoUnfortunately for me, all of my C/C++ is in the embedded space (by that I mean, I am thrilled to do embedded programming. but it's C), so a lot of the nicer features of C++ either aren't available to me (unsupported by the compiler), or are too expensive to use (dynamic dispatch, exceptions). Your Option implementation is definitely interesting; I may crib it some day. Half my consternation comes from an itchy feeling of "why am I inventing this, when Rust already does it!" that perpetually nags at me. It's entirely a hangup that I make myself get over, but it's still there.