简体   繁体   English

为什么const auto&p {nullptr}工作而auto * p {nullptr}不能在C ++ 17中工作?

[英]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.

相关问题 C ++ 17,为什么自动非类型模板参数不能与SFINAE一起使用 - C++17, why doesn't auto non-type template parameter work with SFINAE 为什么“ auto ch = unsigned char {&#39;p&#39;}”不能在C ++ 17下编译? - Why doesn't “auto ch = unsigned char{'p'}” compile under C++ 17? 为什么 shared_ptr<int> ; p=空指针; 编译?</int> - Why does shared_ptr<int> p; p=nullptr; compile? 为什么 nullptr 不需要 header 而 nullptr_t 需要 - why does nullptr not require header while nullptr_t does 如果我将p!= nullptr更改为* p!=&#39;\\ 0&#39;,那么它可以工作,但是为什么呢? - If I change p!=nullptr into *p!='\0', then it works, but why? 为什么unique_ptr重载重置(指针p =指针())和重置(nullptr_t)? - Why does unique_ptr overload reset(pointer p = pointer()) and reset(nullptr_t)? GCC 和 Clang 不编译 std::hash<std::nullptr_t> 在 C++17 中 - GCC and Clang don't compile std::hash<std::nullptr_t> in C++17 为什么我不能用 nullptr 初始化一个自动推导的指针? - Why can't I initialize an auto deduced pointer with nullptr? 由nullptr初始化的C ++ 11自动变量 - C++11 auto variable initialized by nullptr 为什么SFINAE在这里似乎不支持nullptr重载? - Why doesn't SFINAE appear to work with nullptr overload here?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM