2

In normal c++ there are pointers which are indicated with a NULL if they are not pointing to any object.

class* object1 = NULL; //NULL is a special value that indicates
                       //that the pointer is not pointing to any object.

if(object1  == NULL) {
    cout << "the pointer is not pointing to any object" << endl;
}
else {
    cout << "the pointer is pointing to any object" << endl;
} 

So how would that look like with C++/CLI Handles? I have found this on the internet. Can someone tell me if im right about this?

class^ object2 = nullptr;
if(object2 == nullptr){
    cout << "the pointer is not pointing to any object" << endl;
}
else {
    cout << "the pointer is pointing to any object" << endl;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
delorax
  • 45
  • 5
  • 2
    Yes you are right. Also you would use nullptr instead of NULL in modern C++(11 and up). – Łukasz Daniluk Jun 19 '15 at 23:20
  • @LukaszDaniluk Oh well in school we always used NULL (only used pointers, no handles). So what's the big difference betweens those two and what is the reason why you should use nullptr instead of NULL? – delorax Jun 19 '15 at 23:24
  • 2
    C++11 standardized and cleaned up NULL. In the old days it was more or less a pointer to 0. Now it's still basically a pointer to zero, but with a less easily abused wrapper. http://stackoverflow.com/questions/1282295/what-exactly-is-nullptr – user4581301 Jun 19 '15 at 23:29
  • 1
    What happened when you simply... tried it...? – Lightness Races in Orbit Jun 19 '15 at 23:42

1 Answers1

1

You should not use NULL in C++. Opt for nullptr.

Consider this:

void some_function(some_class* test);
void some_function(int test);

int main()
{
    some_function(NULL);
}

Since we humans interpret NULL as a pointer "type," a programmer might expect the first overload to be called. But NULL is often defined as integer 0 -- and thus the compiler would select the second. This isn't a problem if you understand what's happening, but it isn't strongly intuitive.

In addition, 0 is a valid memory address. In desktop programming we generally don't allocate data to address 0, but it could be valid in some other environment. So what can we do to check an allocation at 0?

To stop the ambiguity, C++ features an explicit nullptr. It is not an integer, it has its own special type and cannot be misinterpreted: This pointer has a strongly-typed empty value.

Litty
  • 1,856
  • 1
  • 16
  • 35