Compilation error : 'this' cannot be implicitly captured in this context

本小妞迷上赌 提交于 2020-08-01 09:32:19

问题


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;});

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

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";
        }

    }

回答1:


You need to capture the this pointer:

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


来源:https://stackoverflow.com/questions/38595834/compilation-error-this-cannot-be-implicitly-captured-in-this-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!