Using the initializer lists is encouraged in general. Now let's say I have the following code (trivial example just to make the question clearer):
class foo
{
public:
foo(ptr1* a, ptr2* b) : m_a(a), m_b(b), m_val(a->val) {}
/* code and members here */
};
I would like to check that a
is not NULL before it tries to dereference it to get val
. Is there any way I can perform a sanity check there?
Use the ternary operator:
#include <cstdio>
class Test
{
int x;
public:
Test(int *px)
: x (px ? *px : -1)
{
printf("%d\n", x);
}
};
int main(int argc, char *argv[])
{
Test(NULL);
return 0;
}
The above sample outputs -1
.
You can try:
foo(ptr1* a, ptr2* b) : m_a(a), m_b(b), m_val(a==nullptr ? 0 : a->val) {}
Alternatively, if a==nullptr
is an error in programming logic, you can use an assert() to catch it while unit-testing your debug builds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With