在查看一些代码时,我遇到了一个包含以下行的结构:
if (const auto& foo = std::get_if<MyType>(&bar)) // note the ampersand!
哪里bar
是 std::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& foo
,const
在 auto
部分是限定的,即指针而不是指针。然后 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/