5

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) {}  
};
2

3 Answers 3

6

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.

4

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 };
2

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.

3
  • Hi. Thanks. Yes it is true and that include also usage of value '0' for the null pointer and 'NULL' (credit to PIOTR S. stackoverflow.com/users/3953764/piotr-s who deleted its response..don't know why). Nov 25, 2014 at 8:29
  • in C++11 NULL is still (void*)0 for retro compatibility. That's why the new literal nullptr had to be introduced.
    – dau_sama
    Nov 25, 2014 at 9:06
  • @dau_sama: No, and that was never the case. In every C++ standard, NULL has had an integral type. Could be 0, could be 0L, could be quite a few other things in theory, but (void*)0 is not an integral type.
    – MSalters
    Nov 25, 2014 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.