gpt4 book ai didi

c++ - lambda 表达式的右值和左值引用 - gcc 与 msvc

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:54 44 4
gpt4 key购买 nike

在 C++ 中,将右值隐式转换为左值引用是非法的。考虑以下代码,其中左值引用绑定(bind)到右值(lambda):

int main()
{
auto& f = []() -> void {};
return 0;
}

gcc (4.8.1) 不接受这样的代码(完全有道理)。但是,Microsoft 编译器确实接受它,这意味着它要么接受非标准代码,要么 C++ 允许左值引用绑定(bind)到右值 lambda 表达式的特殊情况。

问题:哪个假设是正确的?

最佳答案

您问题的核心是:rvalues 可以绑定(bind)到 non-const lvalue 引用吗?

标准说rvalues 只能绑定(bind)到 const lvalue 引用。

我相信相关的标准段落是 8.5.3/5:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

...

  • Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference.

但是,Microsoft 有一个长期存在的“功能”允许这种非标准行为,这解释了您所看到的情况。

关于c++ - lambda 表达式的右值和左值引用 - gcc 与 msvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17127652/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com