2 ms·
> Always check for null. Kind of annoying and lots of people don't for whatever reason. use assert or some custom always-assert-even-on-release macro. > Use r
by gpderetta 9y ago
> Always check for null. Kind of annoying and lots of people don't for whatever reason.
use assert or some custom always-assert-even-on-release macro.
> Use references. As you say, annoying because then you can't have null (sensibly) even when it would be really useful.
well, only use references for non nullable pointers. Otherwise use plain (or smart) pointers.
> Use std::optional<int&> or something like that. I only just thought of this and don't know if it would work, but I bet it's a pain.
std::optional<T&> is unfortunately not part of C++17, mostly because people couldn't agree on operator= semantics:
int x = 1;
int y = 2;
std::optional<int&> oint = x;
oint = y;
// which one is true?
assert(x == y); // deep assign
assert(&*oint == &y); // rebind
boost::optional supports references and IIRC rebinds on plain assignment.