C ++ nullptrt_t as an argument in constructor

Reading some code I found a class that only accepts the new C ++ 11 nullptr_t as parameter. The class is as follows.

Is it right that I can build an object using only nullptr ?

 class CA { public: CA(nullptr_t) {} }; 
+5
source share
3 answers

I will correct that the only thing that I can build an object using exclusively nullptr?

Not. This is described in §4.10 [conv.ptr]:

The null pointer constant of an integral type can be converted to a prvalue of type std::nullptr_t .

where the null pointer constant is defined as follows:

The null pointer constant is an integer literal (2.14.2) with a value of 0 or a value of the class std::nullptr_t .

In other words, your constructor can also be called with various integer literals of the value 0:

 CA{ 0 }; CA{ 0u }; CA{ 0LL }; CA{ 0x0 }; 
+4
source

The standard indicates in clause 2.2.14.1 that:

The pointer literal is the nullptr keyword. This value is of type std::nullptr_t . [Note: std::nullptr_t is a separate type that is neither a pointer type nor a pointer to a member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or a null element pointer value. -endnote]

The only prvalue of type nullptr_t is nullptr , which is then converted to another type of pointer, following the rules specified in paragraphs. 4.10 and § 4.11.

Other integer literals can be converted to a value of type std::nullptr_t according to §4.10.1:

The null pointer constant is an integer literal (2.14.2) with a value of 0 or prvalue of type std::nullptr_t .

This way you can use a mediation literal with a value of zero or nullptr .

In particular:

  • 0
  • 0u , 0u
  • 0l , 0l
  • 0ul , 0ul , 0ul , 0ul
  • 0ll , 0ll
  • 0ull , 0ull , 0ull
  • nullptr
  • NULL

Perhaps I missed some cases, so I could not fix me.

+6
source

According to the documentation:

std :: nullptr_t - null pointer literal type, nullptr.

This means that you can only build this object with nullptr or the corresponding integral value (as in the explanation below). Check out this example as it shows the situation when you need it.

+2
source

Source: https://habr.com/ru/post/1207643/


All Articles