Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal C++ to test the this-pointer in a member function?

Tags:

c++

null

this

I have an application involving objects of different class types. The objects are referenced by pointers. A null pointer signifies that the associated object does not exist. Currently the calling codes is cumbersome, because each time it uses a pointer to an object, it tests the pointer value for null, and take some appropriate action it is null. Because the default action to be taken in the case of non-existence depends on the type of object, I would prefer to encode it in the classes for the objects themselves rather than in the calling program. This results in constructions like the following:

class C
{ ... 
  void member_func() //non-virtual !
  { if (this) { do something with the object ... }
    else { take some default action }
  }
  ...
};

Clearly the member function cannot be virtual, because the lookup table does not exist when the object does not exist, and the virtual call would fail. But is this code legal C++ for non-virtual member functions? It seems to work correctly for the compilers I have tried it on, but I am worried about possible non-portability. In the standard I can’t find a clause that either expressly allows or expressly prohibits such constructions.

like image 565
user1958486 Avatar asked Dec 01 '22 04:12

user1958486


1 Answers

this will never be null in a member function so the check you perform is useless.

As pointed by Matthieu M. in a comment, if you do something like this in your code:

C* c = 0; 
c->member();

This would cause undefined behavior and that is something bad.

like image 107
Ivaylo Strandjev Avatar answered Dec 02 '22 16:12

Ivaylo Strandjev