lundi 22 mai 2017

What's the use of casting NULL to SomeType* in C++?

I'm currently grinding through some third-party C++ code that looks rather odd to me (I started out with C++11). One of the many things that left me puzzled, are the many instances of static_cast from NULL to some pointer type:

SomeClass* someClassPtr = static_cast<SomeClass*>(NULL);

I know you can cast pointers e.g. from a base class pointer into a derived class pointer, but there is absolutely no inheritance going on here. As far as I can see, this should be enough:

SomeClass* someClassPtr = NULL;

But the only cases in this code, where NULL does not get casted to a specific pointer type, are pointers in vectors and other containers:

SomeOtherClass.vecOfSomeClassPtr[i] = NULL;

So my questions are:

  • Is this simply old-style (or even C-style) code from before there was nullptr?
  • Is/was casting NULL necessary for other things than down-/upcasting when working with inheritance?
  • Or am I missing something completely?

And in case I haven't gotten it wrong so far:
I first replaced all instances of static_cast<type*>(NULL) with NULL and later nullptr, to see if that would break anything: Nope. The compiler doesn't protest and the program still seems to work as expected. But I know pointers can be tricky little bastards, so:

  • What pitfalls about the use of nullptr did I probably miss?

PS: Yes, I did use the search and yes, I did find similar questions on C code. But this is C++ code and I wanted to know for sure, instead of just assuming something.

Aucun commentaire:

Enregistrer un commentaire