Scott Jones Scott Jones - 1 year ago 129
C++ Question

Null propagation operator in C++

Has anyone implemented a null propagation operator in C++, similar to that used in functional languages? I'm thinking of some clever template solution, possibly akin to the propagating behavior of operator->.

By request, a bit of fleshing out...

Let's suppose we have a chain of objects from a graph, like

(sorry, Law of Demeter). Suppose any one of these could be null, and should be tested before dereferencing. Then the code suddenly becomes much more complicated:

if( !foo )
return nullptr;
if( !foo->bar )
return nullptr;
return foo->bar->baz;

I'd like to "factor out" the null checks with some kind of compact syntax like this:

foo?->bar?->baz // imaginary null-propagation syntax

Now, of course it doesn't have to look like that, just be nearly as compact. I suppose what's needed is a monad in C++, enabling the null test and a 'continuation'. It would be great to avoid macros and lambdas, but that's probably not possible. I could imagine overloading operator->() at each step and short-circuiting out if
was null. But that's very intrusive. An ideal solution would wrap each object in the chain.

Answer Source

At this stage in your design it might be a radical departure, but perhaps consider using the Null Object Pattern. Then you don't need any null checks at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download