I 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.