将基类的引用传递给 boost::thread 并在派生类中调用虚函数是否有效

Will it work to pass a reference to a base class to boost::thread, and have virtual functions in the derived class called?

本文关键字:调用 派生 有效 是否 函数 thread 引用 基类 boost      更新时间:2023-10-16

假设我有:

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寿命。

@GManNickG的评论是最干净的答案,并且非常有效。 Boost.Ref是要走的路。

thread t(boost::ref(*b));