31

This definition works:

const auto &b{nullptr};

while this fails:

auto *b{nullptr};

I have tried to compile this in Visual C++, GCC, and Clang. They all complain "cannot deduce type".

In the second case, shouldn't b be deduced to have some type like std::nullptr_t?

3
  • 2
    did you mean to use auto b{nullptr}; ? Commented Sep 11, 2018 at 11:15
  • if you think the second bwould have type std::nullptr_t, what type do you think the first b has? Commented Sep 11, 2018 at 11:24
  • 3
    Am I the only one that thinks std::nullptr_t b; is more readable? Commented Sep 11, 2018 at 14:29

3 Answers 3

37

It's because you declare b to be a pointer, and initialize it to be a null pointer. But a null pointer to what type of data you don't say, so the compiler can't deduce the type.

If you want b to be a std::nullptr_t object, you should drop the asterisk:

auto b{nullptr};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I have just realized that nullptr has type std::nullptr_t which is not a pointer.... It is strange but make sense in this case.
@felix It ceases to be strange when you take into account that nullptr is convertible to both all pointer types and also all member pointer types.
16

decltype(nullptr) is std::nullptr_t.

so with

const auto &b{nullptr}; // auto is std::nullptr_t
// b is a reference to a temporary (with lifetime extension)

but nullptr is NOT a pointer (even if it is convertible to).

so auto *b{nullptr}; is invalid.

You might use instead

auto b{nullptr}; // auto is std::nullptr_t

Comments

13

nullptr is of type std::nullptr_t. As a nullptr does not point to anything, there is no corresponding pointee type for std::nullptr_t (you are not allowed to dereference a nullptr), hence

auto *b { nullptr};

requests a type that does not exist. If you want b to be of type nullptr_t simply write

auto b { nullptr};

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.