线程中的简单函数调用

时间:2018-11-22 23:53:24

标签: multithreading c++11

class base 
{ 
public: 
    virtual void fun_1() { cout << "base-1\n"; } 
    virtual void fun_2() { cout << "base-2\n"; } 

}; 

class derived : public base 
{ 
public: 
    void fun_1() { cout << "derived-1\n"; } 
    void fun_2() { cout << "derived-2\n"; 
    } 
}; 


class caller
{
    private:
        derived d;
        unique_ptr<base> b = make_unique<derived>(d);

    public:
        void me()
        {
            b->fun_2(); //? How to do this in thread
            // std::thread t(std::bind(&base::fun_2, b), this);
            // t.join();
        }
};

int main() 
{  
    caller c;    
    c.me();
    return 0;
}

我写了一个小程序来一起学习智能指针和虚函数。现在我陷入困境,如何在线程中调用b-> fun_2(),我无法更改基类和派生类。我还必须使用unique_ptr,并且不能更改为shared_ptr。另外,如果可能的话,请取消注释我评论的行,也请解释错误消息。

1 个答案:

答案 0 :(得分:1)

只需这样做:

void me()
{
    std::thread t(&base::fun_2, std::move(b));
    t.join();
}

您的错误消息是由于尝试创建不允许的unique_ptr副本所致。如果您确实需要这种类型的呼叫(使用 bind ),请像这样使用它:

std::thread t(std::bind(&base::fun_2, std::ref(b)));

std::thread t(std::bind(&base::fun_2, b.get()));