capture 如何将基数 class 中的 this 派生为 lambda 函数?

How capture derivated this in base class into lambda function?

我想编写一个实现基础 class 及其派生基础的程序。 我必须在基础 class 中执行一个线程,该线程调用在派生的 class.

中实现的纯虚函数

当我编译和执行程序时,Base::func() 被调用而不是 Derivated::func() 并且我的程序崩溃,因为它无法执行纯虚函数。我必须做什么才能执行派生函数。

注意: 可以存在多个派生的 class,所以我不能显式使用 Derivated::func()

class Base {
private:
    std::thread *t = NULL;
    virtual void func() = 0;


public:
    void foo() {
        std::cout << "Base::foo() executed" << std::endl;

        this->t = new std::thread([this]() {
            while (true) {
                func();
            }
        });
    }
};

class Derivated : public Base {
public:
    void func() {
        std::cout << "Derivated::func() executed" << std::endl;
    }
};

int main() {
    Derivated d;
    d.foo();
}

我期待这样的结果:

Base::foo() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed
...

但这是出现:

Base::foo() executed
pure virtual method called
terminate called without an active exception
Aborted

当一个线程启动时,没有尝试加入它,所以进程在 main 中调用 d.foo(); 后愉快地终止。

如果给线程一个getter,在classBase

std::thread * theThread() { return t; }

在你的 main:

int main() {
    Derivated d;
    d.foo();

    d.theThread()->join();
}

这样主线程就会被阻塞,而另一个线程可以自由地继续(和继续)。

这是一个适合我的例子:

#include <iostream>
#include <memory>
#include <thread>

class Base {
private:
    std::unique_ptr<std::thread> t;
    virtual void func() = 0;

public:
    void foo() {
        std::cout << "Base::foo() executed" << std::endl;    
        t = std::make_unique<std::thread>([this]() {
            for (int i=1; i<= 5; i++) {
                this->func();
            }
        });
        t->join();
    }
};

class Derivated : public Base {
public:
    void func() {
        std::cout << "Derivated::func() executed" << std::endl;
    }
};

int main() {
    Derivated d;
    d.foo();

}

输出:

Base::foo() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed
Derivated::func() executed