c++ - 常量自动引用绑定(bind)到(空)指针 - 实际类型是什么?

标签 c++ pointers reference c++17 auto

在查看一些代码时,我遇到了一个包含以下行的结构:

if (const auto& foo = std::get_if<MyType>(&bar)) // note the ampersand!

哪里barstd::variant<MyType, OtherType> .这里的问题是 get_if may return a null pointer而且我不明白为什么该声明有效。

考虑这个类似的 MCVE:

#include <iostream>

struct Foo { int a = 42; };

Foo* f() { return nullptr; }

int main() {
    const auto& foo = f();          // Returns a nullptr that binds to Foo*& - UB?
    //static_assert(std::is_same<decltype(foo), const Foo*&>::value); // -> Fails
    //const Foo*& bar = f(); // -> Fails

    if (foo)    std::cout << foo->a << std::endl;
    else        std::cout << "nullpointer" << std::endl;
}

第一行main()工作正常,我希望是 bar 的类型成为const Foo*& ,但静态断言失败。毫不奇怪,以下行也无法通过 cannot bind non-const lvalue reference of type 'const Foo*&' to an rvalue of type 'const Foo*' 进行编译。 .

main 的第一条语句发生了什么?这个 UB 或标准是否包含一些允许它合法的隐藏 secret ? bar 的类型是什么?

最佳答案

请注意,对于 const auto& fooconstauto 部分是限定的,即指针而不是指针。然后 foo 的类型将是 Foo* const &,这是一个const 的引用(指向非-const Foo),但不是 const Foo* &,它是对非const引用>(指向 const Foo 的指针)。

const 的左值引用可以绑定(bind)到 f() 返回的右值,所以 const auto& foo = f();工作正常; const Foo*& bar = f(); 将不起作用,因为 bar 是对非 const 的左值引用;不能绑定(bind)到右值。将 bar 的类型更改为 const Foo * const &Foo* const &(与 foo 相同)让它发挥作用。

关于c++ - 常量自动引用绑定(bind)到(空)指针 - 实际类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055888/

相关文章:

c++ - 无法使用辅助链表合并排序链表

c - 如何让字符串数组的值不变?

node.js - 在 Node.js 上使用 mongoose 通过字符串键入多对多关系

c++ - 为什么将 unsigned long 与负数进行比较会导致 false?

c++ - Linux -> C++ 代码 : Object Serialization

C - 如何将多个值分配给 HashMap 中的同一个键?

java - JNI : Overhead of holding Java object references within the native code?

c++ - 调用常量对象参数的方法

c++ - 在共享内存中的 boost 图中插入 boost vector

C++11 替代 boost::checked_delete