c++ - 为什么在 lambda 中通过引用捕获的值被破坏了?

标签 c++ c++11 lambda boost-asio

<分区>

可重复的例子:

#include <iostream>
#include <boost/asio/io_service.hpp>

boost::asio::io_service io_service;

void test1(int t_a)
{
    std::cout << "in test1: t_a = " << t_a << std::endl;
}

void test2(int t_a)
{
    std::cout << "in test2: t_a = " << t_a << std::endl;

    io_service.post([&t_a]()
    {
        std::cout << "in test2 post lambda: t_a = " << t_a << std::endl;
        test1(t_a);
    });
}

int main(int, char**)
{
    int a = 42;

    for (;;) {
        try
        {
            test2(a);
            io_service.run();
            break;
        }
        catch (std::exception & e)
        {

        }
    }
}

输出:

in test2: t_a = 42
in test2 post lambda: t_a = 16451253
in test1: t_a = 16451253
Press any key to continue . . .

这是为什么呢?按值捕获正如我所期望的那样工作,但为什么按引用捕获表现得像这样?

注意 int 此处仅作为示例,考虑任何不利于按值传递的大对象(例如可消耗拷贝)

为什么我将 test1test2 声明为 test1(const int& t_a)test2(const int& t_a) 那么一切正常吗?

最佳答案

t_a 的引用仅在void test2(int t_a) 范围内有效。 在您的案例中按值(value)捕获。

关于c++ - 为什么在 lambda 中通过引用捕获的值被破坏了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571895/

相关文章:

c++ - 将初始化列表传递给基于 vector 的构造函数

c++ - 如何删除 Qt 中 QDoubleSpinBox 的 setfill ('0' ) 特征?

c++ - lambda 函数是否需要任何头文件?

Python 闭包和单元格(闭包值)

node.js - 如何使用 NodeJS 提高 AWS Lambda 函数的性能?

c++ - 未使用的变量 'class' [-Wunused-variable] - 错误/警告

c++ - 试图从函数返回 std::ifstream

c++ - 返回类型模板(enable_if)禁止什么?

c++ - static_cast 没有按预期处理优先级

c# - LINQ 从 String[] 追加到 StringBuilder