假设我有:

class Base
{
    public:

        void operator()()
        {
            this->run();
        }

        virtual void run () {}
}

class Derived : public Base
{
    public:

        virtual void run ()
        {
            // Will this be called when the boost::thread runs?
        }
}

int main()
{
    Base * b = new Derived();
    boost::thread t(*b); // <-- which "run()" function will be called - Base or Derived?
    t.join();
    delete b;
}


从测试中,我无法调用Derived::run()。我是在做错什么,还是这不可能?

最佳答案

通过传递*b,您实际上是“切片” Derived对象,即按值传递Base实例。
您应该通过指针(或智能指针)传递Derived函子,如下所示:

thread t(&Derived::operator(), b); // boost::bind is used here implicitly


当然,要注意b的寿命。

关于c++ - 将对基类的引用传递给boost::thread并在派生类中调用虚拟函数是否可行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13487246/

10-15 00:33