Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I perform sanity checking in the initializer list of a constructor?

Tags:

c++

assert

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?

like image 215
Samaursa Avatar asked Jan 26 '12 04:01

Samaursa


2 Answers

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.

like image 148
ta.speot.is Avatar answered Sep 30 '22 02:09

ta.speot.is


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.

like image 22
kfmfe04 Avatar answered Sep 30 '22 04:09

kfmfe04