【问题标题】:Simple function call in thread线程中的简单函数调用
【发布时间】:2018-11-22 23:53:24
【问题描述】:
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。如果可能,请在取消注释我评论的行时解释错误消息。

【问题讨论】:

  • std::thread t(std::bind(&amp;base::fun_2, b.get()));std::thread t([this](){ b-&gt;fun_2(); });

标签: multithreading c++11


【解决方案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()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2015-11-14
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多