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->fun2(),我无法更改基类和派生类。我还必须使用unique_ptr,不能更改为shared_ptr。如果可能的话,请在取消注释我注释的行时解释错误信息。
发布于 2018-11-23 06:49:04
就这样做吧:
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()));https://stackoverflow.com/questions/53439209
复制相似问题