Can I perform a health check in the list of constructor initializers?

The use of initializer lists is generally recommended. Now suppose I have the following code (a trivial example 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 ait is not NULL before it tries to dereference it to receive val. Is there a way I can perform a sanity check?

+5
source share
2 answers

Use 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 examples of outputs -1.

+5
source

You can try:

foo(ptr1* a, ptr2* b) : m_a(a), m_b(b), m_val(a==nullptr ? 0 : a->val) {}

, a==nullptr ​​ , assert(), .

+1

All Articles