简体   繁体   English

C ++ Lambda捕获搞乱局部变量值

[英]C++ Lambda capture messing up local variable value

I am not sure whether this is a VS 2010 problem or I am misunderstanding something completely. 我不确定这是VS 2010问题还是我完全误解了一些问题。 I am creating a boost thread via a lambda function which needs to modify a local variable: 我正在通过lambda函数创建一个boost函数,该函数需要修改一个局部变量:

    auto oCurrTime( boost::posix_time::microsec_clock::universal_time() );
    auto spRequestSequenceThread = make_unique<boost::thread>( [&oCurrTime, this]()
    {
        while ( !checkAgainstSpecificTime(oCurrTime) )
        {
            ...
        }
        :
        :
    }

Before creating the thread, oCurrTime is something like 2864273654234872634, but within the thread this value gets lost and oCurrTime immediately is something like 487465847564875465, rendering the while loop (where a time difference to some specific Time is evaluated) useless. 在创建线程之前,oCurrTime类似于2864273654234872634,但是在线程中该值丢失并且oCurrTime立即类似于487465847564875465,渲染while循环(其中评估某个特定时间的时间差)是无用的。

Thanks a lot for help. 非常感谢您的帮助。

PS: The above code is part of a function of a class PS:上面的代码是类的函数的一部分

It look like you execute your thread from class method - you provide this in lambda capture list. 看起来你从类方法执行你的线程 - 你在lambda捕获列表中提供this This also means oCurrTime is local variable, so if you capture it by reference : you use & , then when your thread executes oCurrTime will be removed from stack because scope when it was defined already ended. 这也意味着oCurrTime是局部变量,所以如果你通过引用捕获它:你使用& ,那么当你的线程执行时, oCurrTime将从堆栈中删除,因为定义它的范围已经结束。

The solution is to pass oCurrTime by value (remove & ) if it is possible, or join your thread before your method ends - also if that is possible. 解决方案是通过值传递oCurrTime (如果可能的话,删除& ),或者在方法结束之前加入你的线程 - 如果可能的话。 You could also make oCurrTime a class variable. 您还可以使oCurrTime成为类变量。

As you're capturing it by reference [&oCurrTime] 当您通过引用[&oCurrTime]捕获它时
If oCurrTime goes out of scope you will have a dangling reference . 如果oCurrTime超出范围,您将有一个悬空参考

One solution could be to capture by value. 一种解决方案可能是按价值捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM