为什么在lambda中通过引用捕获不会改变变量的类型?

Inc*_*ble 7 c++ lambda c++14

我认为通过引用捕获会更改变量的类型.让我们考虑以下示例:

#include <cassert>
#include <type_traits>

int main()
{
    int x = 0;
    int& x_ref = x;
    const int x_const = x;
    const int& x_const_ref = x_const;

    auto lambda = [&]()
    {
        static_assert(std::is_same<decltype(x), int>::value, "!");
        static_assert(std::is_same<decltype(x_ref), int&>::value, "!");
        static_assert(std::is_same<decltype(x_const), const int>::value, "!");
        static_assert(std::is_same<decltype(x_const_ref), const int&>::value, "!");
    };

    lambda();
}
Run Code Online (Sandbox Code Playgroud)

没有检查失败,因此保留了原始变量的类型.那么,通过引用捕获如何真正起作用?我想如果用户通过引用捕获,则将具有相同名称的新变量引入本地范围以具有原始变量的引用类型.但似乎事实并非如此.

问题:这是什么动机?还是我误解了什么?

sky*_*ack 3

\n

我认为如果用户通过引用捕获,则具有相同名称的新变量将被引入本地范围以具有原始变量的引用类型。

\n
\n\n

标准说(强调我的):

\n\n
\n

如果实体被隐式或显式捕获但未通过副本捕获,则实体\xc2\xa0 通过引用\xc2\xa0 捕获。对于通过引用捕获的实体,是否在闭包类型中声明其他未命名的非静态数据成员是未指定的。如果声明,此类非静态数据成员应为文字类型。

\n
\n\n

因此你的期望是错误的。通过引用捕获并不意味着创建对外部作用域中的对象的本地引用

\n\n
\n\n

作为旁注,请考虑以下事项:

\n\n
int x;\nauto l = [&x](){ return [&x](){} }();\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您的期望是正确的,x那么将是对lambda 内的引用的引用l,这是 C++ 中不存在的东西。

\n