Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does const auto &p{nullptr} work while auto *p{nullptr} doesn't in C++17?

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?

like image 312
felix Avatar asked Sep 11 '18 11:09

felix


People also ask

What does const auto do?

C++ auto auto, const, and references The auto keyword by itself represents a value type, similar to int or char . It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively. These modifiers can be combined.

What is Auto& in C++?

As explained above, the auto keyword in C++ detects the data type of a variable by itself. This means that we can replace the data type of a variable with the keyword auto in C++. The compiler will automatically detect the variable's data type at compile time.

How do I get rid of const?

The statement int* c = const_cast<int>(b) returns a pointer c that refers to a without the const qualification of a . This process of using const_cast to remove the const qualification of an object is called casting away constness. Consequently the compiler does allow the function call f(c) .

Why is const correctness important?

The benefit of const correctness is that it prevents you from inadvertently modifying something you didn't expect would be modified.


3 Answers

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};
like image 189
Some programmer dude Avatar answered Oct 26 '22 06:10

Some programmer dude


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
like image 16
Jarod42 Avatar answered Oct 26 '22 06:10

Jarod42


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};
like image 12
463035818_is_not_a_number Avatar answered Oct 26 '22 06:10

463035818_is_not_a_number