Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ nullptrt_t as argument in a constructor

Tags:

c++11

nullptr

Reading some code I found a class accepting just the new C++11 nullptr_t as parameter. The class looks like the one below.

Am I correct that the only thing I can construct an object by using exclusively nullptr?

class CA {
 public:
 CA(nullptr_t) {}  
};
like image 991
Abruzzo Forte e Gentile Avatar asked Nov 25 '14 07:11

Abruzzo Forte e Gentile


3 Answers

The standard specifies, at §2.14.7.1, that:

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

The only prvalue of type nullptr_t is nullptr which is then convertible to other pointer type following the rules specified in §4.10 and §4.11.

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

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

Therefore you can use an interger literal with value zero or nullptr.

Specifically:

  • 0
  • 0u, 0U
  • 0l, 0L
  • 0ul, 0uL, 0Ul, 0UL
  • 0ll, 0LL
  • 0ull, 0uLL, 0ULL
  • nullptr
  • NULL

I might be missing some cases, so fell free to correct me.

like image 196
Shoe Avatar answered Nov 15 '22 02:11

Shoe


Am I correct that the only thing I can construct an object by using exclusively nullptr?

No. This is covered in §4.10 [conv.ptr]:

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

where a null pointer constant is defined as follows:

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

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

CA{ 0 };
CA{ 0u };
CA{ 0LL };
CA{ 0x0 };
like image 4
Piotr Skotnicki Avatar answered Nov 15 '22 01:11

Piotr Skotnicki


According to the documentation:

std::nullptr_t is the type of the null pointer literal, nullptr.

Which means yes, you can construct this object only with nullptr or a corresponding integral value (as in the answer below explained). Check out this example as it shows a situation where u need it.

like image 2
LMF Avatar answered Nov 15 '22 02:11

LMF