[英]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. 我试图在Visual C ++,GCC和Clang中编译它。 They all complain "cannot deduce type".
他们都抱怨“不能推断出类型”。
In the second case, shouldn't b
be deduced to have some type like std::nullptr_t
? 在第二种情况下,不应该
b
可以推断有一些类型一样std::nullptr_t
?
It's because you declare b
to be a pointer , and initialize it to be a null pointer. 这是因为你声明
b
是一个指针 ,并将其初始化为空指针。 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: 如果你想让
b
成为std::nullptr_t
对象,你应该删除星号:
auto b{nullptr};
decltype(nullptr)
is std::nullptr_t
. decltype(nullptr)
是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). 但是
nullptr
不是一个指针(即使它可以转换为)。
so auto *b{nullptr};
所以
auto *b{nullptr};
is invalid. 是无效的。
You might use instead 你可以改用
auto b{nullptr}; // auto is std::nullptr_t
nullptr
is of type std::nullptr_t
. nullptr
的类型为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 由于
nullptr
没有指向任何东西, std::nullptr_t
没有相应的指针类型(你不允许取消引用nullptr
),因此
auto *b { nullptr};
requests a type that does not exist. 请求一个不存在的类型。 If you want
b
to be of type nullptr_t
simply write 如果你想
b
的类型为nullptr_t
只需写
auto b { nullptr};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.