简体   繁体   English

C ++变量周围的堆栈已损坏

[英]C++ Stack around variable is corrupted

I am trying to implement a timer, which takes a function pointer as a parameter and a time in milliseconds. 我正在尝试实现一个计时器,该计时器将函数指针作为参数和以毫秒为单位的时间。 After the time is passed, the function should be called in a separate thread. 时间过去之后,应在单独的线程中调用该函数。 The code looks as follows: 该代码如下所示:

class timer
{
public:
    void schedule(void(*function)(), int time)
    {
        std::thread t = std::thread([&]
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(time));
                function(); 
            });
        t.detach();
    }
};

The main method looks as follows: 主要方法如下:

#define LOG(x) std::cout << x << std::endl;


timer t1;
timer t2;
timer t3;
t1.schedule([] {LOG("t1 done")}, 2000);
t2.schedule([] {LOG("t2 done")}, 3000);
t3.schedule([] {LOG("t3 done")}, 4000);
std::this_thread::sleep_for(std::chrono::seconds(20));

The exception is as follows: 异常如下:

Run-Time Check Failure #2 - Stack around the variable 't1' was corrupted.

The issue here is you are capturing by reference in your lambda. 这里的问题是您正在通过lambda中的引用来捕获。 This means that it is possible for you to call detach and exit from schedule before the operator() of the lambda is called. 这意味着您可以在调用lambda的operator()之前调用detach并退出schedule If that happens then when you try to use time you are accessing a dangling reference. 如果发生这种情况,那么当您尝试使用time您将访问悬挂的参考。

The solution here is to capture by value instead. 解决方案是按值捕获。 This means you get a copy and it doesn't matter when the operator() is called as the lambda doesn't rely on anything. 这意味着您将获得一份副本,而调用operator()则无所谓,因为lambda并不依赖任何东西。

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

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