编译错误:无法在此上下文中隐式捕获“this" [英] Compilation error : 'this' cannot be implicitly captured in this context

查看:54
本文介绍了编译错误:无法在此上下文中隐式捕获“this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个 condition_variable 来处理线程,但在这一行出现编译错误:

I am trying to add a condition_variable to handle threads, but get a compilation error at this line:

this->cv.wait(lk, []{return this->ready;});

看起来变量 this->ready 的 'this' 不在正确的范围内.

Looks like the for the variable this->ready, the 'this' is not in the right scope.

在 Java 中,这可以用 TestThread.this 来处理,C++ 中有没有做同样的事情?

In Java this can be handled with TestThread.this, is there anything in C++ doing the same?

void TestThread::Thread_Activity()
    {
        std::cout << "Thread started \n";
        // Wait until ThreadA() sends data
        {
            std::unique_lock<std::mutex> lk(m);
            this->cv.wait(lk, []{return ready;});
        }

        std::cout << "Thread is processing data\n";
        data += " after processing";
        // Send data back to ThreadA through the condition variable
        {
           // std::lock_guard<std::mutex> lk(m);
            processed = true;
           // std::cout << "Thread B signals data processing completed\n";
        }

    }

推荐答案

需要捕获this指针:

this->cv.wait(lk, [this]{return ready;});

这篇关于编译错误:无法在此上下文中隐式捕获“this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆