0

假设我有:

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()被召唤。我做错了什么,还是这是不可能的?

4

2 回答 2

2

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

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

当然,要注意b寿命。

于 2012-11-21T06:04:45.043 回答
0

@GManNickG 的评论是最干净的答案,并且效果很好。Boost.Ref 是要走的路。

thread t(boost::ref(*b));
于 2012-11-30T13:23:32.373 回答