1

Let's say whe have

class Foo{

public:
       bool   error;
       ......
       bool isValid(){return error==false;}
};

and somewhere

Foo *aFoo=NULL;

I usually would do if (aFoo!=NULL && aFoo->isValid()).....

But what if in the isValid method I test the nullity:

bool isValid(){return this!=NULL && error==false)

That would simplify the external testing with simply calling if (aFoo->isValid())

I've tested it in some compilers and it works but I wonder if it is standard and could cause problems when porting to other environments.

CashCow
  • 30,981
  • 5
  • 61
  • 92
tru7
  • 6,348
  • 5
  • 35
  • 59
  • 1
    I don't know if it is valid, but I think that even if it is. Any way in my opinion it may be very hard to maintain a client code which assume that the class method implementation checks for nullity. – MaMazav Sep 15 '14 at 09:23
  • 4
    it is definitely not valid to dereference a nullptr – vlad_tepesch Sep 15 '14 at 09:23
  • 1
    Im not quite sure, but I believe this cannot work as `this` within a class cannot be `NULL`, which means that the check in the method is unnecessary; on the other hand, a method call on a null object is undefined behaviour. Is that right? – Codor Sep 15 '14 at 09:23
  • 3
    `I've tested it in some compilers and it works` One of the worst ways to determine if a C++ construct is valid or not. – PaulMcKenzie Sep 15 '14 at 09:29
  • Yes @PaulMcKenzie, but that was only the firs step. Second one is checking in StackOverflow :-) – tru7 Sep 15 '14 at 09:55

3 Answers3

5

The compiler is free to optimize away the check -- calling any non-static member of any class through an invalid (or NULL pointer) is undefined behavior. Please don't do this.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
4

Generally it would be bad design and in standard C++ it doesn't make much sense as your internal NULL check implies that you would call a null pointer, which is undefined behavior.

This topic was discusses here: Checking if this is null

Community
  • 1
  • 1
pdeschain
  • 1,411
  • 12
  • 21
4

Why not simply a namespace-scope function like this?

bool isValid(Foo* f) {return f && f->isValid();}

An if-Statement like

if (aFoo->isValid())

Implies that the pointer is pointing to a valid object. It would be a huge source of confusion and very error prone.

Finally, your code would indeed invoke undefined behavior - aFoo->isValid is per definition equivalent to (*aFoo).isValid:

N3337, §5.2.5/2

The expression E1->E2 is converted to the equivalent form (*(E1)).E2;

which would dereference a null pointer to obtain a null reference, which is clearly undefined:

N3337, §8.3.2/5

[ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. […] — end note ]

CashCow
  • 30,981
  • 5
  • 61
  • 92
Columbo
  • 60,038
  • 8
  • 155
  • 203