jwernerny
jwernerny

Reputation: 7048

C++11 Magic to test and assign from pointer if not nullptr

Okay, I believe in defensive programming. I assume that if I get a pointer it might be null (especially when using GSOAP). Therefore before I try to use the value of the pointer, I always check to make sure the pointer is not null.

In my current code, this is leading to a lot of nearly identical statements.

if (res->A) {
    item.out_trace->a = *res->A;
}
if (res->B) {
    item.out_trace->b = *res->B;
}
if (res->C) {
    item.out_trace->b = *res->C;
}

I realize that I could always go and define a macro for this, but I am wondering if there is a neat C++11 trick to do that. I would love something like the C# ??

// Set y to the value of x if x is NOT null; otherwise, 
// if x = null, set y to -1. 
int y = x ?? -1;

Thanks.

Upvotes: 0

Views: 131

Answers (1)

Adam H. Peterson
Adam H. Peterson

Reputation: 4601

Perhaps a template like this would meet your need:

template<typename T>
T safe_get( T const *ptr, T defval = T{} ) {
    return ptr ? *ptr : std::move(defval);
}

It could be used like this:

item.out_trace->a = safe_get( rez->A );

Ideally it would be inlined and effectively zero-overhead (other than the inherent overhead of doing the safety check and having a branch, of course).

Upvotes: 3

Related Questions