【发布时间】: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(&base::fun_2, b.get()));或std::thread t([this](){ b->fun_2(); });
标签: multithreading c++11