AksharRoop
AksharRoop

Reputation: 2293

nullptr vs __nullptr

I was just wondering why there are two ways to specify null pointer. I have been going through the link, but did not get clear understanding of its use.

Can someone give a good example of when to use what?

Upvotes: 12

Views: 4749

Answers (3)

Ezh
Ezh

Reputation: 629

This is the case when Micosoft wrote a good explanation (https://learn.microsoft.com/en-us/cpp/extensions/nullptr-cpp-component-extensions?view=msvc-170) - it is identical to the actepted answer in this thread: "in native code use nullptr, in C++/CLI use nullptr for managed objects and __nullptr for native pointer".

However, it the very same article Microsoft shown examples, which completely ignore this advice:

// mcpp_nullptr.cpp
// compile with: /clr
value class V {};
ref class G {};
void f(System::Object ^) {}

int main() {
// Native pointer.
   int *pN = nullptr;
// Managed handle.
   G ^pG = nullptr;

So in fact you can use nullptr for both managed and native pointers. Compiler doesn't generate error or warning in this case. Also code works like expected. And only if you want to explicitly say in your code "hey, this is a NATIVE pointer, look, this is important!" - you can use __nullptr. So this is more about showing the meaning of nullptr to another programmer, not about the code corectness for compiler.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942438

The C++/CLI language already had a nullptr keyword since 2005. That caused a problem when C++11 adopted the nullptr keyword for C++. Now there are two, one for managed code and another for native code. The C++/CLI compiler can compile both. So you have to use __nullptr when you mean the native null pointer, nullptr when you mean the managed null pointer.

This is only relevant when you compile with /clr in effect. Write C++/CLI code in other words. Just use plain nullptr in C++ code.

Upvotes: 25

Some programmer dude
Some programmer dude

Reputation: 409482

If I read it correctly, you should use nullptr for managed pointers, and __nullptr for unmanaged pointer. However, since nullptr can be used for both managed an unmanaged pointer, I personally don't see a reason to use __nullptr.

Upvotes: 0

Related Questions