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

标签 c++ visual-c++ gcc c++11

在 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/

相关文章:

c++ - 删除后我应该分配我的指针 0 吗?

c - SQL Server 2005与VC++的连接(代码)

c++ - 遍历字符串并组合每个循环中的前一个字符

c++ - 停止回溯

windows - 应用程序验证程序无法在此处的 3 台单独的 Windows 机器上启动

c++ - 如何在 Visual C++ 中手动修改名称?

X86 和 ARM 上 C 中指针和整数的比较

c++ - gcc 4.6.1 错误的严格别名警告

c++ - 为什么 QCustomPlot 在绘制大数据时速度太慢?

c++ - lnk4022 : undecorated symbol - how to fix?